package com.jpcc.vw.onlineRadio.service;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Popup;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.CustomIntent;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Binder;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.RemoteException;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;

import com.cns.android.account.CnsAccountInfo;
import com.cns.android.account.CnsAccountManager;
import com.cns.android.authentication.AppTokenInfo;
import com.cns.android.authentication.AppTokenManager;
import com.cns.android.helper.VehicleInfoHelper;
import com.cns.android.media.MediaInfoManager;
import com.cns.android.onlineservice.OnlineServiceManager;
import com.cns.android.sds.SDSResponse;
import com.cns.android.vehicle.VehicleManager;
import com.danikula.videocache.HttpProxyCacheServer;
import com.google.android.exoplayer2.C;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.j256.ormlite.dao.Dao;
import com.j256.ormlite.stmt.DeleteBuilder;
import com.jpcc.vw.callback.NewPayResultListener;
import com.jpcc.vw.mylibrary.PaySdk;
import com.jpcc.vw.onlineRadio.R;
import com.jpcc.vw.onlineRadio.activity.AlbumDetailActivity;
import com.jpcc.vw.onlineRadio.activity.MainActivity;
import com.jpcc.vw.onlineRadio.activity.SettingRadioActivity;
import com.jpcc.vw.onlineRadio.application.MusicApplication;
import com.jpcc.vw.onlineRadio.constants.Actions;
import com.jpcc.vw.onlineRadio.constants.Constants;
import com.jpcc.vw.onlineRadio.db.DatabaseHelperOrm;
import com.jpcc.vw.onlineRadio.db.DownloadTrackDbBean;
import com.jpcc.vw.onlineRadio.db.FavouriteAlbumDbBean;
import com.jpcc.vw.onlineRadio.http.HttpClient;
import com.jpcc.vw.onlineRadio.model.IRadio;
import com.jpcc.vw.onlineRadio.model.action.RadioCountAction;
import com.jpcc.vw.onlineRadio.model.action.RefreshFavStatusAction;
import com.jpcc.vw.onlineRadio.model.action.RefreshPlayingAction;
import com.jpcc.vw.onlineRadio.model.action.RefreshRadioPlayingAction;
import com.jpcc.vw.onlineRadio.model.action.StartPlayerAction;
import com.jpcc.vw.onlineRadio.model.bean.AlbumBrowseBean;
import com.jpcc.vw.onlineRadio.model.bean.AlbumFavouriteBean;
import com.jpcc.vw.onlineRadio.model.bean.Announcer;
import com.jpcc.vw.onlineRadio.model.bean.BaseBean;
import com.jpcc.vw.onlineRadio.model.bean.CnsAccountInfoSelf;
import com.jpcc.vw.onlineRadio.model.bean.CommonAlbumRadioSearchResultBean;
import com.jpcc.vw.onlineRadio.model.bean.CommonFavouritePaiedHistoryEntity;
import com.jpcc.vw.onlineRadio.model.bean.DailyRecommendationBean;
import com.jpcc.vw.onlineRadio.model.bean.LiveRadioDetailBean;
import com.jpcc.vw.onlineRadio.model.bean.NewSearchAlbumResultBean;
import com.jpcc.vw.onlineRadio.model.bean.PaidAlbumsEntity;
import com.jpcc.vw.onlineRadio.model.bean.PaiedAlbumBean;
import com.jpcc.vw.onlineRadio.model.bean.PlaceOrderBean;
import com.jpcc.vw.onlineRadio.model.bean.PlayHistoryEntity;
import com.jpcc.vw.onlineRadio.model.bean.PlayInfoBean;
import com.jpcc.vw.onlineRadio.model.bean.PriceTypeInfoBean;
import com.jpcc.vw.onlineRadio.model.bean.RadioDeailBean;
import com.jpcc.vw.onlineRadio.model.bean.RadioSumBean;
import com.jpcc.vw.onlineRadio.model.bean.RecentAlbumRadioTrackBean;
import com.jpcc.vw.onlineRadio.model.bean.SDSCommonOuterResultBean;
import com.jpcc.vw.onlineRadio.model.bean.SDSCommonResult;
import com.jpcc.vw.onlineRadio.model.bean.SDSOuterResultBean;
import com.jpcc.vw.onlineRadio.model.bean.SDSOuterSpecialResultBean;
import com.jpcc.vw.onlineRadio.model.bean.SDSPlayControlParambean;
import com.jpcc.vw.onlineRadio.model.bean.SDSPlaySpecialStatusBean;
import com.jpcc.vw.onlineRadio.model.bean.SDSPlayStatusBean;
import com.jpcc.vw.onlineRadio.model.bean.SDSStationInfo;
import com.jpcc.vw.onlineRadio.model.bean.SDSearchOnlineStationOuterResultBean;
import com.jpcc.vw.onlineRadio.model.bean.SDSearchOnlineStationResult;
import com.jpcc.vw.onlineRadio.model.bean.SimpleAlbumRadioEntity;
import com.jpcc.vw.onlineRadio.model.bean.SubordinatedAlbum;
import com.jpcc.vw.onlineRadio.model.bean.TileCommand;
import com.jpcc.vw.onlineRadio.model.bean.TopListAlbumBean;
import com.jpcc.vw.onlineRadio.model.bean.TopListBean;
import com.jpcc.vw.onlineRadio.model.bean.TopListData;
import com.jpcc.vw.onlineRadio.model.bean.Track;
import com.jpcc.vw.onlineRadio.model.bean.XiMaLaYaOrderBean;
import com.jpcc.vw.onlineRadio.model.impl.RadioImpl;
import com.jpcc.vw.onlineRadio.receiver.RemoteControlReceiver;
import com.jpcc.vw.onlineRadio.utils.CommonSubscriber;
import com.jpcc.vw.onlineRadio.utils.ConfigReaderUtils;
import com.jpcc.vw.onlineRadio.utils.DeleteFileUtil;
import com.jpcc.vw.onlineRadio.utils.PreferenceUtils;
import com.jpcc.vw.onlineRadio.utils.ProcessInfoUtils;
import com.jpcc.vw.onlineRadio.utils.SyncFavUtils;
import com.jpcc.vw.onlineRadio.utils.ToastUtils;
/*Start by menglingqiang*/
import com.jpcc.vw.onlineRadio.utils.TransformUtils;
import com.jpcc.vw.tracelog.TracelogInterface;
/*End by menglingqiang*/
import com.orhanobut.logger.Logger;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.FileCallBack;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;

import de.greenrobot.event.EventBus;
import okhttp3.Call;
import rx.Observable;
import rx.Subscriber;
import rx.functions.Action0;
import rx.functions.Func1;
import rx.functions.Func2;


/**
 * 播放服务
 */
public class PlayAlbumRadioService extends Service implements OnAlbumRadioPlayerEventListener {
    private static final String TAG = "PlayAlbumRadioService";
    private DatabaseHelperOrm helper = DatabaseHelperOrm.getHelper(PlayAlbumRadioService.this);
    private IRadio radioModel;
    private BroadcastReceiver SDSReceiver;
    private RemoteControlReceiver remoteControlReceiver;
    private BroadcastReceiver networkChangeReceiver;
    private BroadcastReceiver tileReceiver;
    HttpProxyCacheServer proxy;
    private boolean initStart = true;
    //    private VehicleInfoHelper.ManagerServiceConnectionListener accountListener;
    private BroadcastReceiver changeAccountReiver;
    private BroadcastReceiver tokenChangeReceiver;
    private BroadcastReceiver onlineServiceChangeReceiver;
    private BroadcastReceiver popReceiver;
    private BroadcastReceiver payResultReceiver;

    @Override
    public void onChange(RecentAlbumRadioTrackBean radio) {
        if (Constants.isRelease) {
            if(radio==null){
                return;
            }
            File directory = new File("/mnt/tmpnfs/onlinecovericons/");
            if (directory.exists()) {
                for (File subFile : directory.listFiles()) {
                    if (subFile.getName().contains("radio")) {
                        subFile.delete();
                    }
                }
            }
            try {
                MediaInfoManager.getInstance(MusicApplication.GetInstance()).sendFocusedMediaPackageName("com.jpcc.vw.onlineRadio");
                MediaInfoManager.getInstance(MusicApplication.GetInstance()).sendPlayStatus(MediaInfoManager.PLAY_STATUS_PLAYING);
                MediaInfoManager.getInstance(MusicApplication.GetInstance()).sendTileStatus(MediaInfoManager.TILE_STATUS_AVAILABLE, "");
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }
        EventBus.getDefault().post(new RefreshPlayingAction());
        if (radio != null) {
            PreferenceUtils.SaveLastMode(radio);
        }
        if (Constants.isRelease) {
            try {
                MediaInfoManager.getInstance(MusicApplication.GetInstance()).sendPlayMode(false, MediaInfoManager.PLAY_REPEAT_MODE_OFF, MediaInfoManager.PLAY_RANDOM_MODE_OFF);
                if ((!"album".equals(radio.getType())) && (radio.isLive())) {
                    MediaInfoManager.getInstance(MusicApplication.GetInstance()).sendPlayTime(false, 0, 0);
                }
            } catch (RemoteException e) {
            }
        }
        RadioCountAction action = new RadioCountAction();
        action.setEvent("switch");
        action.setModuleId("radio");
        action.setPreserved(false);
        action.setStation(radio.getAlbumName());
        action.setStationId(radio.getAlbumId() + "");
        EventBus.getDefault().post(action);


        Bundle bundle = new Bundle();
        bundle.putString("album", radio.getAlbumName());
//        bundle.putString("artist", radio.getAuthor());
//        bundle.putString("title", radio.getTrackName());


        bundle.putString("artist", AlbumRadioAudioPlayer.get().getPlayMusic().getTrackName());
        bundle.putString("title", AlbumRadioAudioPlayer.get().getPlayMusic().getAlbumName());


        bundle.putString("album_cover_uri", "");
        bundle.putString("radio_id", radio.getAlbumId() + "");


        if (true) {
            File directoryFile = new File("/mnt/tmpnfs/onlinecovericons");
            if (!directoryFile.exists()) {
                directoryFile.mkdir();
            }
            String CoverEndType = ".jpg";
            if ((!TextUtils.isEmpty(radio.getCover()))) {
                if (radio.getCover().contains("png")) {
                    CoverEndType = ".jpg";
                } else {
                    CoverEndType = ".jpg";
                }
            }
//            File RadioCoverFile = new File("/mnt/tmpnfs/onlinecovericons/radio_" + radio.getTrackId() + "_icon" + radio.getCover().substring(radio.getCover().lastIndexOf(".")));
//            Logger.i("RadioCoverFile---->" + "/mnt/tmpnfs/onlinecovericons/radio_" + radio.getTrackId() + "_icon" + radio.getCover().substring(radio.getCover().lastIndexOf(".")));
            File RadioCoverFile = new File("/mnt/tmpnfs/onlinecovericons/radio_" + radio.getTrackId() + "_icon" + CoverEndType);
            Logger.i("RadioCoverFile---->" + "/mnt/tmpnfs/onlinecovericons/radio_" + radio.getTrackId() + "_icon" + CoverEndType);
            if (RadioCoverFile.exists()) {
                RadioCoverFile.delete();
                Logger.i("RadioCoverFile exist---->" + true);
            }
            if ((!TextUtils.isEmpty(radio.getCover())) && (radio.getCover().length() > 3)) {
                Logger.i("RadioCoverFile getCover()---->" + radio.getCover());
//                Logger.i("RadioCoverFile File path---->" + "/mnt/tmpnfs/onlinecovericons/radio_" + radio.getTrackId() + "_icon" + radio.getCover().substring(radio.getCover().lastIndexOf(".")));
                Logger.i("RadioCoverFile File path---->" + "/mnt/tmpnfs/onlinecovericons/radio_" + radio.getTrackId() + "_icon" + CoverEndType);
                OkHttpUtils
                        .get()
                        .url(radio.getCover())
                        .build().execute(new FileCallBack("/mnt/tmpnfs/onlinecovericons", "radio_" + radio.getTrackId() + "_icon" + CoverEndType) {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        Logger.i("RadioCoverFile cover download error---->" + e.toString());
                    }

                    @Override
                    public void onResponse(File response, int id) {
                        RadioCoverFile.setWritable(true, false);
                        RadioCoverFile.setReadable(true, false);
                        Bundle bundle = new Bundle();
                        bundle.putString("album", AlbumRadioAudioPlayer.get().getPlayMusic().getAlbumName());
                        bundle.putString("artist", AlbumRadioAudioPlayer.get().getPlayMusic().getTrackName());
                        bundle.putString("title", AlbumRadioAudioPlayer.get().getPlayMusic().getAlbumName());

//                        Logger.i("RadioCoverFile cover download success---->" + "/mnt/tmpnfs/onlinecovericons/" + "radio_" + radio.getTrackId() + "_icon" + radio.getCover().substring(radio.getCover().lastIndexOf(".")));
//                        bundle.putString("album_cover_uri", "/mnt/tmpnfs/onlinecovericons/" + "radio_" + radio.getTrackId() + "_icon" + radio.getCover().substring(radio.getCover().lastIndexOf(".")));

                        String CoverEndType = ".jpg";
                        if ((!TextUtils.isEmpty(radio.getCover()))) {
                            if (radio.getCover().contains("png")) {
                                CoverEndType = ".jpg";
                            } else {
                                CoverEndType = ".jpg";
                            }
                        }

                        Logger.i("RadioCoverFile cover download success---->" + "/mnt/tmpnfs/onlinecovericons/" + "radio_" + radio.getTrackId() + "_icon" + CoverEndType);
                        bundle.putString("album_cover_uri", "/mnt/tmpnfs/onlinecovericons/" + "radio_" + radio.getTrackId() + "_icon" + CoverEndType);
                        bundle.putString("radio_id", AlbumRadioAudioPlayer.get().getPlayMusic().getAlbumId() + "");
                        if ("album".equals(AlbumRadioAudioPlayer.get().getPlayMusic().getType())) {
                            bundle.putString("radio_type", "album");
                        } else {
                            bundle.putString("radio_type", "radio");
                        }
                        bundle.putString(MediaInfoManager.KEY_GENRE, "");
                        try {
                            if (Constants.isRelease) {
                                MediaInfoManager.getInstance(PlayAlbumRadioService.this).sendMediaInfo(bundle);
                                MediaInfoManager.getInstance(MusicApplication.GetInstance()).sendFocusedMediaPackageName("com.jpcc.vw.onlineRadio");
                                MediaInfoManager.getInstance(MusicApplication.GetInstance()).sendPlayStatus(MediaInfoManager.PLAY_STATUS_PLAYING);
                            }
                            Logger.i("sendMediaInfo----->" + bundle.toString());
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                });
            }
        }


        if (Constants.isRelease) {
            try {
                MediaInfoManager.getInstance(MusicApplication.GetInstance()).sendPlayMode(false, 0, 0);
                Logger.i("sendPlayMode-->" + false);
                MediaInfoManager.getInstance(MusicApplication.GetInstance()).sendPlayButtonVisibility(true);
                MediaInfoManager.getInstance(MusicApplication.GetInstance()).sendFocusedMediaPackageName("com.jpcc.vw.onlineRadio");
                MediaInfoManager.getInstance(MusicApplication.GetInstance()).sendPlayStatus(MediaInfoManager.PLAY_STATUS_PLAYING);
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }

        if ("album".equals(radio.getType())) {
            bundle.putString("radio_type", "album");
        } else {
            bundle.putString("radio_type", "radio");
        }
        bundle.putString(MediaInfoManager.KEY_GENRE, "");
        try {
            if (Constants.isRelease) {
//                MediaInfoManager.getInstance(PlayAlbumRadioService.this).sendMediaInfo(bundle);
            }
            Logger.i("sendMediaInfo----->" + bundle.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }


        if ("album".equals(radio.getType())) {
            HashMap<String, Object> queryMaps = new HashMap<>();
            queryMaps.put("userId", MusicApplication.GetUserId());
            queryMaps.put("trackId", radio.getTrackId());
            try {
                List<RecentAlbumRadioTrackBean> results = helper.getRecentDao().queryForFieldValues(queryMaps);
                if (results.size() == 0) {
                    radio.setTimeStamp(new Date().getTime());
                    helper.getRecentDao().create(radio);
                } else {
                    RecentAlbumRadioTrackBean result = results.get(0);
                    result.setTimeStamp(new Date().getTime());
                    //避免快听完了的时候仍旧
                    if ((double) results.get(0).getCurrentDuration() / results.get(0).getDuration() > 0.97) {
//                        result.setCurrentDuration(0);
                    }
                    result.setFrom(radio.getFrom());
                    helper.getRecentDao().update(result);
//                    AlbumRadioAudioPlayer.get().seek(result.getCurrentDuration());
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
        } else {
            EventBus.getDefault().post(new RefreshRadioPlayingAction());
            HashMap<String, Object> queryMaps = new HashMap<>();
            queryMaps.put("userId", MusicApplication.GetUserId());
            queryMaps.put("albumId", radio.getAlbumId());
            queryMaps.put("trackId", radio.getTrackId());
            try {
                List<RecentAlbumRadioTrackBean> results = helper.getRecentDao().queryForFieldValues(queryMaps);
                if (results.size() == 0) {
                    radio.setTimeStamp(new Date().getTime());
                    radio.setRadioLivingUrl(radio.getTrackUrl());
                    helper.getRecentDao().create(radio);
                } else {
                    RecentAlbumRadioTrackBean result = results.get(0);
                    result.setTimeStamp(new Date().getTime());
                    result.setRadioLivingUrl(radio.getTrackUrl());
                    helper.getRecentDao().update(result);
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void onPlayerStart() {
        if (AlbumRadioAudioPlayer.get().getPlayMusic() != null) {
            SDSOuterSpecialResultBean resultOuter = new SDSOuterSpecialResultBean();
            resultOuter.setDomain("onlineRadio");
            resultOuter.setRequestType("getPlayStatus");
            SDSPlaySpecialStatusBean inner = new SDSPlaySpecialStatusBean();
            inner.setSignalInfo("com.jpcc.vw.onlineRadio");
            resultOuter.setRequestResult(inner);
            try {
                if (Constants.isRelease) {
                    MediaInfoManager.getInstance(MusicApplication.GetInstance()).sendFocusedMediaPackageName("com.jpcc.vw.onlineRadio");
                    SDSResponse.getInstance(this).sendResponse("SDS_0x01", new Gson().toJson(resultOuter), true);
                    MediaInfoManager.getInstance(MusicApplication.GetInstance()).sendPlayStatus(MediaInfoManager.PLAY_STATUS_PLAYING);
                }
            } catch (RemoteException e) {
                e.printStackTrace();
            }

            String CoverEndType = ".jpg";
            if ((!TextUtils.isEmpty(AlbumRadioAudioPlayer.get().getPlayMusic().getCover()))) {
                if (AlbumRadioAudioPlayer.get().getPlayMusic().getCover().contains("png")) {
                    CoverEndType = ".jpg";
                } else {
                    CoverEndType = ".jpg";
                }
            }

//            File directory = new File("/mnt/tmpnfs/onlinecovericons/radio_" + AlbumRadioAudioPlayer.get().getPlayMusic().getTrackId() + "_icon" + AlbumRadioAudioPlayer.get().getPlayMusic().getCover().substring(AlbumRadioAudioPlayer.get().getPlayMusic().getCover().lastIndexOf(".")));
            File directory = new File("/mnt/tmpnfs/onlinecovericons/radio_" + AlbumRadioAudioPlayer.get().getPlayMusic().getTrackId() + "_icon" + CoverEndType);
            RadioCountAction action = new RadioCountAction();
            action.setEvent("switch");
            action.setModuleId("radio");
            action.setPreserved(false);
            action.setStation(AlbumRadioAudioPlayer.get().getPlayMusic().getAlbumName());
            action.setStationId(AlbumRadioAudioPlayer.get().getPlayMusic().getAlbumId() + "");
            EventBus.getDefault().post(action);


            Bundle bundle = new Bundle();
            bundle.putString("album", AlbumRadioAudioPlayer.get().getPlayMusic().getAlbumName());
//            bundle.putString("artist", AlbumRadioAudioPlayer.get().getPlayMusic().getAuthor());
//            bundle.putString("title", AlbumRadioAudioPlayer.get().getPlayMusic().getTrackName());


            bundle.putString("artist", AlbumRadioAudioPlayer.get().getPlayMusic().getTrackName());
            bundle.putString("title", AlbumRadioAudioPlayer.get().getPlayMusic().getAlbumName());


            bundle.putString("radio_id", AlbumRadioAudioPlayer.get().getPlayMusic().getAlbumId() + "");


            if ("album".equals(AlbumRadioAudioPlayer.get().getPlayMusic().getType())) {
                bundle.putString("radio_type", "album");
            } else {
                bundle.putString("radio_type", "radio");
            }
            bundle.putString(MediaInfoManager.KEY_GENRE, "");
            try {
                if (Constants.isRelease) {
                    if (!directory.exists()) {


                        RecentAlbumRadioTrackBean radio = AlbumRadioAudioPlayer.get().getPlayMusic();
                        if ((!TextUtils.isEmpty(radio.getCover())) && (radio.getCover().length() > 3)) {
                            Logger.i("RadioCoverFile getCover()---->" + radio.getCover());
//                            Logger.i("RadioCoverFile File path---->" + "/mnt/tmpnfs/onlinecovericons/radio_" + radio.getTrackId() + "_icon" + radio.getCover().substring(radio.getCover().lastIndexOf(".")));
                            Logger.i("RadioCoverFile File path---->" + "/mnt/tmpnfs/onlinecovericons/radio_" + radio.getTrackId() + "_icon" + CoverEndType);
                            OkHttpUtils
                                    .get()
                                    .url(radio.getCover())
                                    .build().execute(new FileCallBack("/mnt/tmpnfs/onlinecovericons", "radio_" + radio.getTrackId() + "_icon" + CoverEndType) {
                                @Override
                                public void onError(Call call, Exception e, int id) {
                                    Logger.i("RadioCoverFile cover download error---->" + e.toString());
                                }

                                @Override
                                public void onResponse(File response, int id) {
                                    response.setWritable(true, false);
                                    response.setReadable(true, false);
                                    Bundle bundle = new Bundle();
                                    bundle.putString("album", AlbumRadioAudioPlayer.get().getPlayMusic().getAlbumName());
//                                    bundle.putString("artist", AlbumRadioAudioPlayer.get().getPlayMusic().getAuthor());
//                                    bundle.putString("title", AlbumRadioAudioPlayer.get().getPlayMusic().getTrackName());


                                    bundle.putString("artist", AlbumRadioAudioPlayer.get().getPlayMusic().getTrackName());
                                    bundle.putString("title", AlbumRadioAudioPlayer.get().getPlayMusic().getAlbumName());

                                    String CoverEndType = ".jpg";
                                    if ((!TextUtils.isEmpty(AlbumRadioAudioPlayer.get().getPlayMusic().getCover()))) {
                                        if (AlbumRadioAudioPlayer.get().getPlayMusic().getCover().contains("png")) {
                                            CoverEndType = ".jpg";
                                        } else {
                                            CoverEndType = ".jpg";
                                        }
                                    }


                                    Logger.i("RadioCoverFile cover download success---->" + "/mnt/tmpnfs/onlinecovericons/" + "radio_" + radio.getTrackId() + "_icon" + CoverEndType);
//                                    bundle.putString("album_cover_uri", "/mnt/tmpnfs/onlinecovericons/" + "radio_" + radio.getTrackId() + "_icon" + radio.getCover().substring(radio.getCover().lastIndexOf(".")));
                                    bundle.putString("album_cover_uri", "/mnt/tmpnfs/onlinecovericons/" + "radio_" + radio.getTrackId() + "_icon" + CoverEndType);
                                    bundle.putString("radio_id", AlbumRadioAudioPlayer.get().getPlayMusic().getAlbumId() + "");
                                    if ("album".equals(AlbumRadioAudioPlayer.get().getPlayMusic().getType())) {
                                        bundle.putString("radio_type", "album");
                                    } else {
                                        bundle.putString("radio_type", "radio");
                                    }
                                    bundle.putString(MediaInfoManager.KEY_GENRE, "");
                                    try {
                                        if (Constants.isRelease) {
                                            MediaInfoManager.getInstance(MusicApplication.GetInstance()).sendTileStatus(MediaInfoManager.TILE_STATUS_AVAILABLE, "");
                                            MediaInfoManager.getInstance(PlayAlbumRadioService.this).sendMediaInfo(bundle);
                                            MediaInfoManager.getInstance(MusicApplication.GetInstance()).sendFocusedMediaPackageName("com.jpcc.vw.onlineRadio");
                                            MediaInfoManager.getInstance(MusicApplication.GetInstance()).sendPlayStatus(MediaInfoManager.PLAY_STATUS_PLAYING);
                                        }
                                        Logger.i("sendMediaInfo----->" + bundle.toString());
                                    } catch (Exception e) {
                                        e.printStackTrace();
                                    }
                                }
                            });
                        }


                    } else {
                        MediaInfoManager.getInstance(MusicApplication.GetInstance()).sendTileStatus(MediaInfoManager.TILE_STATUS_AVAILABLE, "");
                        bundle.putString("album_cover_uri", "/mnt/tmpnfs/onlinecovericons/radio_" + AlbumRadioAudioPlayer.get().getPlayMusic().getTrackId() + "_icon" + CoverEndType);
                        MediaInfoManager.getInstance(PlayAlbumRadioService.this).sendMediaInfo(bundle);


                        MediaInfoManager.getInstance(MusicApplication.GetInstance()).sendFocusedMediaPackageName("com.jpcc.vw.onlineRadio");
                        MediaInfoManager.getInstance(MusicApplication.GetInstance()).sendPlayStatus(MediaInfoManager.PLAY_STATUS_PLAYING);
                    }
                }
                Logger.i("sendMediaInfo----->" + bundle.toString());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void onPlayerPause() {
        if (AlbumRadioAudioPlayer.get().getPlayMusic() != null) {

            RadioCountAction action = new RadioCountAction();
            action.setEvent("switch");
            action.setModuleId("radio");
            action.setPreserved(false);
            action.setStation(AlbumRadioAudioPlayer.get().getPlayMusic().getAlbumName());
            action.setStationId(AlbumRadioAudioPlayer.get().getPlayMusic().getAlbumId() + "");
            EventBus.getDefault().post(action);


            Bundle bundle = new Bundle();
            bundle.putString("album", AlbumRadioAudioPlayer.get().getPlayMusic().getAlbumName());
//            bundle.putString("artist", AlbumRadioAudioPlayer.get().getPlayMusic().getAuthor());
//            bundle.putString("title", AlbumRadioAudioPlayer.get().getPlayMusic().getTrackName());


            bundle.putString("artist", AlbumRadioAudioPlayer.get().getPlayMusic().getTrackName());
            bundle.putString("title", AlbumRadioAudioPlayer.get().getPlayMusic().getAlbumName());


            String CoverEndType = ".jpg";
            if ((!TextUtils.isEmpty(AlbumRadioAudioPlayer.get().getPlayMusic().getCover()))) {
                if (AlbumRadioAudioPlayer.get().getPlayMusic().getCover().contains("png")) {
                    CoverEndType = ".jpg";
                } else {
                    CoverEndType = ".jpg";
                }
            }


            File file = new File("/mnt/tmpnfs/onlinecovericons/radio_" + AlbumRadioAudioPlayer.get().getPlayMusic().getTrackId() + "_icon" + CoverEndType);
            if (file.exists()) {
                bundle.putString("album_cover_uri", "/mnt/tmpnfs/onlinecovericons/radio_" + AlbumRadioAudioPlayer.get().getPlayMusic().getTrackId() + "_icon" + CoverEndType);
            } else {
                bundle.putString("album_cover_uri", "");
            }

            bundle.putString("radio_id", AlbumRadioAudioPlayer.get().getPlayMusic().getAlbumId() + "");


            if ("album".equals(AlbumRadioAudioPlayer.get().getPlayMusic().getType())) {
                bundle.putString("radio_type", "album");
            } else {
                bundle.putString("radio_type", "radio");
            }
            bundle.putString(MediaInfoManager.KEY_GENRE, "");
            try {
                if (Constants.isRelease) {
//                    MediaInfoManager.getInstance(PlayAlbumRadioService.this).sendMediaInfo(bundle);
//                    MediaInfoManager.getInstance(MusicApplication.GetInstance()).sendFocusedMediaPackageName("com.jpcc.vw.onlineRadio");
                    MediaInfoManager.getInstance(MusicApplication.GetInstance()).sendPlayStatus(MediaInfoManager.PLAY_STATUS_PAUSED);
                }
                Logger.i("sendMediaInfo----->" + bundle.toString());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void onPublish(int progress, RecentAlbumRadioTrackBean radio) {
        if (radio == null) {
            return;
        }
        if (Constants.isRelease) {
            //删除为了测试
            PreferenceUtils.SaveFrontStatus();
        }



        Logger.i("ServicePublish-->"+progress);

        if (radio != null) {
            RecentAlbumRadioTrackBean innerRadio = radio;
            innerRadio.setCurrentDuration(progress);
            PreferenceUtils.SaveLastMode(radio);
        }

        if(Constants.isRelease){
            try {
                MediaInfoManager.getInstance(MusicApplication.GetInstance()).sendFocusedMediaPackageName("com.jpcc.vw.onlineRadio");
                MediaInfoManager.getInstance(MusicApplication.GetInstance()).sendPlayStatus(MediaInfoManager.PLAY_STATUS_PLAYING);
                MediaInfoManager.getInstance(MusicApplication.GetInstance()).sendTileStatus(MediaInfoManager.TILE_STATUS_AVAILABLE, "");
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }


        if ("album".equals(radio.getType())) {
            try {
                Logger.i("onPublish-->" + MusicApplication.GetUserId());
                RecentAlbumRadioTrackBean result = helper.getRecentDao().queryBuilder().where().eq("userId", MusicApplication.GetUserId()).and().eq("trackId", radio.getTrackId()).queryForFirst();
                if (result != null) {
                    result.setCurrentDuration(progress);
                    result.setFrom(radio.getFrom());
                    helper.getRecentDao().update(result);
                    if (Constants.isRelease) {
                        //删除为了测试
                        try {
                            MediaInfoManager.getInstance(MusicApplication.GetInstance()).sendPlayTime(true, radio.getDuration(), progress);
                        } catch (RemoteException e) {
                            e.printStackTrace();
                        }
                    }
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
        } else {

            if (Constants.isRelease) {
                //删除为了测试
                try {
                    if (radio.isLive()) {
                        Logger.i("tile-->" + radio.isLive());
                        Logger.i("sendPlayMode-->" + false);
                    } else {
                        MediaInfoManager.getInstance(MusicApplication.GetInstance()).sendPlayTime(true, radio.getDuration(), progress);
                        Logger.i("tile-->" + radio.isLive());
                        Logger.i("tile duration-->" + radio.getDuration());
                        Logger.i("tile progress-->" + progress);
                        Logger.i("sendPlayMode-->" + false);
                    }
                } catch (RemoteException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @Override
    public void onBufferingUpdate(int percent) {

    }

    @Override
    public void onPlayAlbumFinished(RecentAlbumRadioTrackBean result) {
        if (result.getFrom() == 0) {
            doNextAlbumForFav(result.getAlbumId());
        } else if (result.getFrom() == 1) {
            doNextAlbumForDownload(result.getAlbumId());
        } else if (result.getFrom() == 2) {
//            doNextAlbumForpaied(result.getAlbumId());
        } else if (result.getFrom() == 4) {
//            if ("radio".equals(result.getType()) && false) {//!result.isLive()) {
//                doNextListenbackRadio(result);
//            }
//            if ("radio".equals(result.getType()) && !result.isLive()) {
//                gotoLiveProgram(result);
//            }
        }


//        if ("album".equals(AlbumRadioAudioPlayer.get().getPlayMusic().getType())) {
//            AlbumRadioAudioPlayer.get().seekTo(0);
////            AlbumRadioAudioPlayer.get().pausePlayer(false);
//            Constants.FLAG_PAUSE_MANUAL = true;
//            Constants.FLAG_FOCUS_ON_SELF = false;
//            AlbumRadioAudioPlayer.get().playPauseAbandonFocus();
//        }


    }


    private void gotoLiveProgram(RecentAlbumRadioTrackBean result) {

        /*Start by menglingqiang*/
        Date dt = new Date();
        try {
            TracelogInterface inter = MusicApplication.getLogInterface();
            if (inter != null) {
                inter.sendLogData(dt.toString(), dt.toString(), PlayAlbumRadioService.this.getClass().getName(), "DEBUG", null, "GetPlayingProgramDetail Request");
            } else {
                Log.e("JPCC", "inter == null");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        /*End by menglingqiang*/

        radioModel.GetPlayingProgramDetail(result.getAlbumId()).subscribe(new CommonSubscriber<LiveRadioDetailBean>() {
            @Override
            public void onSuccess(LiveRadioDetailBean response) {
                Track track = new Track();
                SubordinatedAlbum subordinatedAlbum = new SubordinatedAlbum();
                subordinatedAlbum.setId(result.getAlbumId());
                subordinatedAlbum.setAlbumTitle(result.getAlbumName());
                Announcer announcer = new Announcer();
                announcer.setNickname("");
                track.setId(response.getData().getId());
                track.setTrackTitle(response.getData().getProgramName());
                track.setCoverUrlLarge(response.getData().getBackPicUrl());
                track.setPlayUrl32(response.getData().getRate24AacUrl());
                track.setCanDownload(false);
                track.setDownloadUrl("");
                track.type = "radio";
                track.setSubordinatedAlbum(subordinatedAlbum);
                track.setAnnouncer(announcer);
                track.setLive(true);
                List<Track> sources = new ArrayList<>();
                Constants.LastModeFlag = false;
                sources.add(track);
                AlbumRadioAudioPlayer.get().setOnSources(sources, 0, 4, -1);
                /*Start by menglingqiang*/
                Date dt = new Date();
                try {
                    TracelogInterface inter = MusicApplication.getLogInterface();
                    if (inter != null) {
                        inter.sendLogData(dt.toString(), dt.toString(), PlayAlbumRadioService.this.getClass().getName(), "DEBUG", "400", "GetPlayingProgramDetail onSuccess");
                    } else {
                        Log.e("JPCC", "inter == null");
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                /*End by menglingqiang*/
            }

            @Override
            public void onFailure(BaseBean response) {
                ToastUtils.show(response.getStatusMessage());
                /*Start by menglingqiang*/
                Date dt = new Date();
                try {
                    TracelogInterface inter = MusicApplication.getLogInterface();
                    if (inter != null) {
                        inter.sendLogData(dt.toString(), dt.toString(), PlayAlbumRadioService.this.getClass().getName(), "ERROR", "400", "GetPlayingProgramDetail onFailure");
                    } else {
                        Log.e("JPCC", "inter == null");
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                /*End by menglingqiang*/
            }
        });
    }

    @Override
    public void onFinishTrack() {

    }

    @Override
    public void onToPrevAlbum(RecentAlbumRadioTrackBean source) {
        if (source != null && source.getFrom() == 0) {
            List<CommonFavouritePaiedHistoryEntity> local_datas = new ArrayList<>();
            List<FavouriteAlbumDbBean> local_db = new ArrayList<>();
            try {
                local_db.addAll(helper.getFavouriteDao().queryBuilder().orderBy("timeStamp", false).where().eq("userId", MusicApplication.GetUserId()).query());
                if (local_db.size() > 1) {
                    for (int index = 0; index < local_db.size(); index++) {
                        if (local_db.get(index).getId() == source.getAlbumId()) {
                            if (index > 0) {

                                /*Start by menglingqiang*/
                                Date dt = new Date();
                                try {
                                    TracelogInterface inter = MusicApplication.getLogInterface();
                                    if (inter != null) {
                                        inter.sendLogData(dt.toString(), dt.toString(), PlayAlbumRadioService.this.getClass().getName(), "DEBUG", "400", "GetAlbumBrowse Request");
                                    } else {
                                        Log.e("JPCC", "inter == null");
                                    }
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                                /*End by menglingqiang*/

                                radioModel.GetAlbumBrowse(local_db.get(index - 1).getId(), 1).subscribe(new CommonSubscriber<AlbumBrowseBean>() {
                                    @Override
                                    public void onSuccess(AlbumBrowseBean response) {
                                        if (response.getData().getTracks() != null && response.getData().getTracks().size() > 0) {
                                            List<Track> sour = new ArrayList<>();
                                            sour.addAll(response.getData().getTracks());
                                            AlbumRadioAudioPlayer.get().setOnSources(sour, 0, 0, -1);
                                        }
                                        /*Start by menglingqiang*/
                                        Date dt = new Date();
                                        try {
                                            TracelogInterface inter = MusicApplication.getLogInterface();
                                            if (inter != null) {
                                                inter.sendLogData(dt.toString(), dt.toString(), PlayAlbumRadioService.this.getClass().getName(), "DEBUG", "400", "GetAlbumBrowse onSuccess");
                                            } else {
                                                Log.e("JPCC", "inter == null");
                                            }
                                        } catch (Exception e) {
                                            e.printStackTrace();
                                        }
                                        /*End by menglingqiang*/
                                    }

                                    @Override
                                    public void onFailure(BaseBean response) {
                                        /*Start by menglingqiang*/
                                        Date dt = new Date();
                                        try {
                                            TracelogInterface inter = MusicApplication.getLogInterface();
                                            if (inter != null) {
                                                inter.sendLogData(dt.toString(), dt.toString(), PlayAlbumRadioService.this.getClass().getName(), "ERROR", "400", "GetAllPaiedAlbum onFailure");
                                            } else {
                                                Log.e("JPCC", "inter == null");
                                            }
                                        } catch (Exception e) {
                                            e.printStackTrace();
                                        }
                                        /*End by menglingqiang*/
                                    }
                                });
                            }
                        }
                    }
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
        } else if (source != null && source.getFrom() == 1) {
            try {
                List<DownloadTrackDbBean> resultQuerys = helper.getDownloadDao().queryBuilder().orderBy("timeStamp", false).groupBy("albumId").where().eq("userId", MusicApplication.GetUserId()).query();
                if (resultQuerys != null && resultQuerys.size() > 1) {
                    for (int index = 0; index < resultQuerys.size(); index++) {
                        if (resultQuerys.get(index).getAlbumId() == source.getAlbumId()) {
                            if (index >= 1) {
                                DownloadTrackDbBean previousDb = resultQuerys.get(index - 1);
                                List<DownloadTrackDbBean> datas = new ArrayList<>();
                                datas.addAll(helper.getDownloadDao().queryBuilder().orderBy("timeStamp", false).where().eq("albumId", previousDb.getAlbumId()).and().eq("userId", MusicApplication.GetUserId()).query());
                                List<Track> infos = new ArrayList<>();
                                for (DownloadTrackDbBean db : datas) {
                                    Track track = new Track();
                                    SubordinatedAlbum subordinatedAlbum = new SubordinatedAlbum();
                                    subordinatedAlbum.setId(db.getAlbumId());
                                    subordinatedAlbum.setAlbumTitle(db.getAlbumName());
                                    Announcer announcer = new Announcer();
                                    announcer.setNickname(db.getAuthor());
                                    track.setId(db.getTrackId());
                                    track.setTrackTitle(db.getTrackName());
                                    track.setCoverUrlLarge(db.getCover());
                                    track.setPlayUrl32(db.getTrackUrl());
                                    track.setCanDownload(false);
                                    track.setDownloadUrl("");
                                    track.type = "album";
                                    track.setDuration(db.getDuration() / 1000);
                                    track.setAnnouncer(announcer);
                                    track.setSubordinatedAlbum(subordinatedAlbum);
                                    infos.add(track);
                                }
                                Constants.LastModeFlag = false;
                                AlbumRadioAudioPlayer.get().setOnSources(infos, 0, 1, -1);
                            }
                        }
                    }
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void onToPayAlumTrack(RecentAlbumRadioTrackBean source) {

    }

    @Override
    public void onGetPlayInfo(long trackId) {
        if (radioModel == null) {
            radioModel = new RadioImpl();
        }
        radioModel.GetPlayInfo(trackId).subscribe(new CommonSubscriber<PlayInfoBean>() {
            @Override
            public void onSuccess(PlayInfoBean response) {
                if (response.getData() != null && !TextUtils.isEmpty(response.getData().getPlayUrl24Aac())) {
                    AlbumRadioAudioPlayer.get().setPlayUrl(response.getData().getPlayUrl24Aac());
                } else {
                    ToastUtils.show(R.string.string_80);
                }
            }

            @Override
            public void onFailure(BaseBean response) {
                ToastUtils.show(response.getStatusMessage());
            }
        });
    }

    @Override
    public void onGetPayDialog(long albumId, long trackId) {
        if (radioModel == null) {
            radioModel = new RadioImpl();
        }
        radioModel.GetPriceInfo(albumId).subscribe(new CommonSubscriber<PriceTypeInfoBean>() {
            @Override
            public void onSuccess(PriceTypeInfoBean response) {


//                NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
//                Intent setAlertIntent = new Intent("com.jpcc.vw.PlayAlbumRadioService");
//                setAlertIntent.putExtra("action", "ClearSearchHistory");
//                PendingIntent pendingIntent = PendingIntent.getBroadcast(PlayAlbumRadioService.this, 0, setAlertIntent, 0);
//                Popup popup = new Popup(getResources().getString(R.string.string_30), getResources().getString(R.string.string_67));
//                popup.setActionOne(getResources().getString(R.string.string_32), pendingIntent);
//                popup.setActionCancel(getResources().getString(R.string.string_33), "cancel");
//                notificationManager.addPopup(0x0002, popup);


                //以声音为单位进行购买
                if (response.getData().getPriceTypeDetail().get(0).getPriceType() == 1) {
//                    dialog = new MaterialDialog.Builder(getActivity()).title(getResources().getString(R.string.string_30)).content(getResources().getString(R.string.string_85)).positiveText(getResources().getString(R.string.string_32)).negativeText(getResources().getString(R.string.string_33)).onPositive(new MaterialDialog.SingleButtonCallback() {
//                        @Override
//                        public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
//                            placeOrder(false, response, trackId, trackId);
//                        }
//                    }).build();
//                    if (MusicApplication.GetInstance().getActivityNum() > 1) {
//                        Intent intent = new Intent(getActivity(), MainActivity.class);
//                        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
//                        startActivity(intent);
//                    }
//                    dialog.show();


                    NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
                    Intent setAlertIntent = new Intent("com.jpcc.vw.PlayAlbumRadioService");
                    setAlertIntent.putExtra("action", "PayForTrack");
                    setAlertIntent.putExtra("isBoughtByAlbum", false);
                    setAlertIntent.putExtra("PriceTypeInfoBean", new Gson().toJson(response));
                    setAlertIntent.putExtra("Id", trackId);
                    setAlertIntent.putExtra("trackId", trackId);
                    PendingIntent pendingIntent = PendingIntent.getBroadcast(PlayAlbumRadioService.this, 0, setAlertIntent, PendingIntent.FLAG_UPDATE_CURRENT);
                    Popup popup = new Popup(getResources().getString(R.string.string_30), getResources().getString(R.string.string_85));
                    popup.setActionOne(getResources().getString(R.string.string_32), pendingIntent);
                    popup.setActionCancel(getResources().getString(R.string.string_33), "cancel");
                    notificationManager.addPopup(0x0001, popup);
                }
                //以专辑为单位进行购买
                else {
//                    placeOrder(true, response, albumId);
//                    if (dialog != null && dialog.isShowing()) {
//                        dialog.dismiss();
//                    }
//                    dialog = new MaterialDialog.Builder(getActivity()).title(getResources().getString(R.string.string_30)).content(getResources().getString(R.string.string_86)).positiveText(getResources().getString(R.string.string_32)).negativeText(getResources().getString(R.string.string_33)).onPositive(new MaterialDialog.SingleButtonCallback() {
//                        @Override
//                        public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
//                            placeOrder(true, response, albumId, trackId);
//                        }
//                    }).build();
//                    if (MusicApplication.GetInstance().getActivityNum() > 1) {
//                        Intent intent = new Intent(getActivity(), MainActivity.class);
//                        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
//                        startActivity(intent);
//                    }
//                    dialog.show();


                    NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
                    Intent setAlertIntent = new Intent("com.jpcc.vw.PlayAlbumRadioService");
                    setAlertIntent.putExtra("action", "PayForTrack");
                    setAlertIntent.putExtra("isBoughtByAlbum", true);
                    setAlertIntent.putExtra("PriceTypeInfoBean", new Gson().toJson(response));
                    setAlertIntent.putExtra("Id", albumId);
                    setAlertIntent.putExtra("trackId", trackId);
                    PendingIntent pendingIntent = PendingIntent.getBroadcast(PlayAlbumRadioService.this, 0, setAlertIntent, PendingIntent.FLAG_UPDATE_CURRENT);
                    Popup popup = new Popup(getResources().getString(R.string.string_30), getResources().getString(R.string.string_86));
                    popup.setActionOne(getResources().getString(R.string.string_32), pendingIntent);
                    popup.setActionCancel(getResources().getString(R.string.string_33), "cancel");
                    notificationManager.addPopup(0x0001, popup);
                }


            }

            @Override
            public void onFailure(BaseBean response) {

            }
        });
    }

    @Override
    public void onGetVIPDialog() {
        Logger.i("onGetVIPDialog()-->打开购买VIP的Pop");
        if (Constants.isRelease) {
            NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
            Intent setAlertIntent = new Intent("com.jpcc.vw.PlayAlbumRadioService");
            setAlertIntent.putExtra("action", "PayForVIP");
            PendingIntent pendingIntent = PendingIntent.getBroadcast(PlayAlbumRadioService.this, 0, setAlertIntent, PendingIntent.FLAG_UPDATE_CURRENT);
            Popup popup = new Popup(getResources().getString(R.string.string_30), getResources().getString(R.string.string_81));
            popup.setActionOne(getResources().getString(R.string.string_32), pendingIntent);
            popup.setActionCancel(getResources().getString(R.string.string_33), "cancel");
            notificationManager.addPopup(0x0001, popup);
        }
    }

    /**
     * 回听列表的数据听完了之后
     * 再加一条当前的直播连接
     *
     * @param result
     */
    private void doNextListenbackRadio(RecentAlbumRadioTrackBean result) {

        /*Start by menglingqiang*/
        Date dt = new Date();
        try {
            TracelogInterface inter = MusicApplication.getLogInterface();
            if (inter != null) {
                inter.sendLogData(dt.toString(), dt.toString(), PlayAlbumRadioService.this.getClass().getName(), "DEBUG", "400", "GetPlayingProgramDetail Request");
            } else {
                Log.e("JPCC", "inter == null");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        /*End by menglingqiang*/

        radioModel.GetPlayingProgramDetail(result.getAlbumId()).subscribe(new CommonSubscriber<LiveRadioDetailBean>() {
            @Override
            public void onSuccess(LiveRadioDetailBean response) {
                List<Track> infos = new ArrayList<>();
                infos.addAll(AlbumRadioAudioPlayer.get().getTracks());
                Track track = new Track();
                track.setId(response.getData().getId());
                track.setTrackTitle(response.getData().getProgramName());
                track.setCoverUrlLarge(response.getData().getBackPicUrl());
                track.setCoverUrlMiddle(response.getData().getBackPicUrl());
                track.setCoverUrlLarge(response.getData().getBackPicUrl());
                Announcer announcer = new Announcer();
//                if (response.getData().getLiveAnnouncers().size() > 0) {
//                    announcer.setNickname(response.getData().getLiveAnnouncers().get(0).getNickname());
//                } else {
//                    announcer.setNickname("");
//                }
                track.setPlayUrl32(response.getData().getRate24AacUrl());
                track.setCanDownload(false);
                track.setDownloadUrl("");
                SubordinatedAlbum subordinatedAlbum = new SubordinatedAlbum();
                subordinatedAlbum.setId(result.getAlbumId());
                subordinatedAlbum.setAlbumTitle(result.getAlbumName());
                track.type = "radio";
                track.setAnnouncer(announcer);
                track.setSubordinatedAlbum(subordinatedAlbum);
                track.setLive(true);
                for (Track tt : infos) {
                    tt.setLive(false);
                }
                infos.add(track);
                AlbumRadioAudioPlayer.get().setOnSourcesForListenbackRadio(infos, infos.size() - 1, 4);
                /*Start by menglingqiang*/
                Date dt = new Date();
                try {
                    TracelogInterface inter = MusicApplication.getLogInterface();
                    if (inter != null) {
                        inter.sendLogData(dt.toString(), dt.toString(), PlayAlbumRadioService.this.getClass().getName(), "DEBUG", "400", "GetPlayingProgramDetail onSuccess");
                    } else {
                        Log.e("JPCC", "inter == null");
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                /*End by menglingqiang*/
            }

            @Override
            public void onFailure(BaseBean response) {
                /*Start by menglingqiang*/
                Date dt = new Date();
                try {
                    TracelogInterface inter = MusicApplication.getLogInterface();
                    if (inter != null) {
                        inter.sendLogData(dt.toString(), dt.toString(), PlayAlbumRadioService.this.getClass().getName(), "ERROR", "400", "GetPlayingProgramDetail onFailure");
                    } else {
                        Log.e("JPCC", "inter == null");
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                /*End by menglingqiang*/
            }
        });
    }


    /**
     * 获取购买的专辑的下一个需要播放的
     *
     * @param albumId
     */
    private void doNextAlbumForpaied(long albumId) {
        radioModel.GetAllPaiedAlbum(1).flatMap(new Func1<PaiedAlbumBean, Observable<AlbumBrowseBean>>() {
            @Override
            public Observable<AlbumBrowseBean> call(PaiedAlbumBean paiedAlbumBean) {
                if (paiedAlbumBean.getData().getPaidAlbums() != null && paiedAlbumBean.getData().getPaidAlbums().size() > 0) {
                    List<PaidAlbumsEntity> datas = new ArrayList<>();
                    datas.addAll(paiedAlbumBean.getData().getPaidAlbums());
                    PaidAlbumsEntity nextPaidAlbumsEntity = null;
                    for (int index = 0; index < datas.size(); index++) {
                        if (datas.get(index).getId() == albumId && index + 1 < datas.size()) {
                            nextPaidAlbumsEntity = datas.get(index + 1);
                        }
                    }
                    if (nextPaidAlbumsEntity == null) {
                        AlbumBrowseBean albumBrowseBean = new AlbumBrowseBean();
                        albumBrowseBean.setCode(-1);
                        return Observable.just(albumBrowseBean);
                    } else {
                        return radioModel.GetAlbumBrowse(nextPaidAlbumsEntity.getId(), 1);
                    }
                } else {
                    AlbumBrowseBean albumBrowseBean = new AlbumBrowseBean();
                    albumBrowseBean.setCode(-1);
                    return Observable.just(albumBrowseBean);
                }
            }
        }).subscribe(new Subscriber<AlbumBrowseBean>() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onNext(AlbumBrowseBean response) {
                if (response.getCode() != -1) {
                    if (response.getData().getTracks() != null && response.getData().getTracks().size() > 0) {
                        List<Track> sour = new ArrayList<>();
                        sour.addAll(response.getData().getTracks());
                        RecentAlbumRadioTrackBean local = null;
                        try {
                            local = helper.getRecentDao().queryBuilder().orderBy("timeStamp", false).where().eq("userId", MusicApplication.GetUserId()).and().eq("albumId", albumId).queryForFirst();
                        } catch (SQLException e) {
                            e.printStackTrace();
                        }
                        int position = -1;
                        for (int index = 0; index < sour.size(); index++) {
                            if (local.getTrackId() == sour.get(index).getId()) {
                                position = index;
                            }
                        }
                        if (position < 0) {
                            return;
                        }
                        AlbumRadioAudioPlayer.get().setOnSources(sour, position, 2, -1);
                    }
                }
            }
        });
    }


    /**
     * 为了播放下载的跨专辑播放
     *
     * @param albumId
     */
    private void doNextAlbumForDownload(long albumId) {
        List<DownloadTrackDbBean> resultQuerys = new ArrayList<>();
        try {
            DownloadTrackDbBean nextDownloadAlbum = null;
            resultQuerys.addAll(helper.getDownloadDao().queryBuilder().orderBy("timeStamp", false).groupBy("albumId").where().eq("userId", MusicApplication.GetUserId()).query());
            for (int index = 0; index < resultQuerys.size(); index++) {
                if (resultQuerys.get(index).getAlbumId() == albumId && index + 1 < resultQuerys.size()) {
                    nextDownloadAlbum = resultQuerys.get(index + 1);
                }
            }
            if (nextDownloadAlbum == null) {
                return;
            }
            List<DownloadTrackDbBean> datas = new ArrayList<>();
            datas.addAll(helper.getDownloadDao().queryBuilder().orderBy("timeStamp", false).where().eq("albumId", nextDownloadAlbum.getAlbumId()).and().eq("userId", MusicApplication.GetUserId()).query());
            List<Track> infos = new ArrayList<>();
            for (DownloadTrackDbBean db : datas) {
                Track track = new Track();
                SubordinatedAlbum subordinatedAlbum = new SubordinatedAlbum();
                subordinatedAlbum.setId(db.getAlbumId());
                subordinatedAlbum.setAlbumTitle(db.getAlbumName());
                Announcer announcer = new Announcer();
                announcer.setNickname(db.getAuthor());
                track.setId(db.getTrackId());
                track.setTrackTitle(db.getTrackName());
                track.setCoverUrlLarge(db.getCover());
                track.setPlayUrl32(db.getTrackUrl());
                track.setCanDownload(false);
                track.setDownloadUrl("");
                track.type = "album";
                track.setDuration(db.getDuration() / 1000);
                track.setAnnouncer(announcer);
                track.setSubordinatedAlbum(subordinatedAlbum);
                infos.add(track);
            }


            RecentAlbumRadioTrackBean local = null;
            try {
                local = helper.getRecentDao().queryBuilder().orderBy("timeStamp", false).where().eq("userId", MusicApplication.GetUserId()).and().eq("albumId", nextDownloadAlbum.getAlbumId()).queryForFirst();
            } catch (SQLException e) {
                e.printStackTrace();
            }

            int positon = -1;
            for (int index = 0; index < infos.size(); index++) {
                if (infos.get(index).getId() == local.getTrackId()) {
                    positon = index;
                }
            }
            if (positon == -1) {
                return;
            }
            AlbumRadioAudioPlayer.get().setOnSources(infos, positon, 1, -1);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }


    /**
     * 自动播放的时候处理俩字与收藏的列表的专辑
     * 跨专辑
     *
     * @param albumId
     */
    private void doNextAlbumForFav(long albumId) {
        try {
            List<FavouriteAlbumDbBean> favs = new ArrayList<>();
            FavouriteAlbumDbBean nextAlbum = null;
            favs.addAll(helper.getFavouriteDao().queryBuilder().orderBy("timeStamp", false).where().eq("userId", MusicApplication.GetUserId()).query());
            for (int index = 0; index < favs.size(); index++) {
                if ((favs.get(index).getId() == albumId) && (index + 1 < favs.size())) {
                    nextAlbum = favs.get(index + 1);
                }
            }
            if (nextAlbum == null) {
                return;
            }
            if ("album".equals(nextAlbum.getType())) {
                FavouriteAlbumDbBean finalNextAlbum1 = nextAlbum;

                /*Start by menglingqiang*/
                Date dt = new Date();
                try {
                    TracelogInterface inter = MusicApplication.getLogInterface();
                    if (inter != null) {
                        inter.sendLogData(dt.toString(), dt.toString(), PlayAlbumRadioService.this.getClass().getName(), "DEBUG", "400", "GetAlbumBrowse Request");
                    } else {
                        Log.e("JPCC", "inter == null");
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                /*End by menglingqiang*/

                radioModel.GetAlbumBrowse(nextAlbum.getId(), 1).subscribe(new CommonSubscriber<AlbumBrowseBean>() {
                    @Override
                    public void onSuccess(AlbumBrowseBean response) {
                        if (response.getData().getTracks() != null && response.getData().getTracks().size() > 0) {
                            List<Track> sour = new ArrayList<>();
                            sour.addAll(response.getData().getTracks());
                            RecentAlbumRadioTrackBean local = null;
//                            try {
//                                local = helper.getRecentDao().queryBuilder().orderBy("timeStamp", false).where().eq("userId", MusicApplication.GetUserId()).and().eq("albumId", finalNextAlbum1.getId()).queryForFirst();
//                            } catch (SQLException e) {
//                                e.printStackTrace();
//                            }
//                            int positon = -1;
//                            for (int index = 0; index < sour.size(); index++) {
//                                if (sour.get(index).getId() == local.getTrackId()) {
//                                    positon = index;
//                                }
//                            }
//                            if (positon == -1) {
//                                return;
//                            }
                            AlbumRadioAudioPlayer.get().setOnSources(sour, 0, 0, -1);
                        }

                        /*Start by menglingqiang*/
                        Date dt = new Date();
                        try {
                            TracelogInterface inter = MusicApplication.getLogInterface();
                            if (inter != null) {
                                inter.sendLogData(dt.toString(), dt.toString(), PlayAlbumRadioService.this.getClass().getName(), "DEBUG", "400", "GetAlbumBrowse onSuccess");
                            } else {
                                Log.e("JPCC", "inter == null");
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        /*End by menglingqiang*/
                    }

                    @Override
                    public void onFailure(BaseBean response) {
                        ToastUtils.show(response.getStatusMessage());
                        /*Start by menglingqiang*/
                        Date dt = new Date();
                        try {
                            TracelogInterface inter = MusicApplication.getLogInterface();
                            if (inter != null) {
                                inter.sendLogData(dt.toString(), dt.toString(), PlayAlbumRadioService.this.getClass().getName(), "ERROR", "400", "GetAlbumBrowse onFailure");
                            } else {
                                Log.e("JPCC", "inter == null");
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        /*End by menglingqiang*/
                    }
                });
            } else {


                long radioId = nextAlbum.getId();
                String radioName = nextAlbum.getName();

                Date today = new Date();
                Calendar c = Calendar.getInstance();
                c.setTime(today);
                int weekday = c.get(Calendar.DAY_OF_WEEK);

                Observable.zip(radioModel.GetPlayingProgramDetail(radioId), radioModel.getLiveSchedules(radioId, weekday - 1), new Func2<LiveRadioDetailBean, RadioDeailBean, RadioSumBean>() {
                    @Override
                    public RadioSumBean call(LiveRadioDetailBean liveRadioDetailBean, RadioDeailBean radioDeailBean) {
                        RadioSumBean response = new RadioSumBean();
                        if (liveRadioDetailBean.getCode() == 0 && radioDeailBean.getCode() == 0) {
                            response.setLiveRadio(liveRadioDetailBean);
                            response.setRadioSchedule(radioDeailBean);
                            return response;
                        }
                        return response;
                    }
                }).subscribe(new Subscriber<RadioSumBean>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onNext(RadioSumBean radioSumBean) {


                        List<Track> sources = new ArrayList<>();

                        if (radioSumBean.getRadioSchedule() != null) {
                            List<RadioDeailBean.RadioSchedule> datas = new ArrayList<>();
                            if (radioSumBean.getRadioSchedule().getData() != null) {
                                datas.addAll(radioSumBean.getRadioSchedule().getData());
                            }
                            for (int index = 0; index < datas.size(); index++) {
                                if (!TextUtils.isEmpty(datas.get(index).getListenBackUrl())) {
                                    RadioDeailBean.RadioSchedule shcedule = datas.get(index);
                                    Track track = new Track();
                                    track.setId(shcedule.getId());
                                    track.setTrackTitle(shcedule.getRelatedProgram().getProgramName());
                                    track.setCoverUrlLarge(shcedule.getRelatedProgram().getBackPicUrl());
                                    track.setCoverUrlMiddle(shcedule.getRelatedProgram().getBackPicUrl());
                                    track.setCoverUrlLarge(shcedule.getRelatedProgram().getBackPicUrl());
                                    Announcer announcer = new Announcer();
                                    announcer.setNickname("");
                                    track.setPlayUrl32(shcedule.getListenBackUrl());
                                    track.setCanDownload(false);
                                    track.setDownloadUrl("");
                                    track.setLive(false);
                                    SubordinatedAlbum subordinatedAlbum = new SubordinatedAlbum();
                                    subordinatedAlbum.setId(radioId);
                                    subordinatedAlbum.setAlbumTitle(radioName);
                                    track.type = "radio";
                                    track.setAnnouncer(announcer);
                                    track.setSubordinatedAlbum(subordinatedAlbum);
                                    sources.add(track);
                                }
                            }
                        }


                        if (radioSumBean.getLiveRadio() != null) {
                            LiveRadioDetailBean response = radioSumBean.getLiveRadio();
                            Track track = new Track();
                            SubordinatedAlbum subordinatedAlbum = new SubordinatedAlbum();
                            subordinatedAlbum.setId(radioId);
                            subordinatedAlbum.setAlbumTitle(radioName);
                            Announcer announcer = new Announcer();
                            announcer.setNickname("");
                            track.setId(response.getData().getId());
                            track.setTrackTitle(response.getData().getProgramName());
                            track.setCoverUrlLarge(response.getData().getBackPicUrl());
                            track.setPlayUrl32(response.getData().getRate24AacUrl());
                            track.setCanDownload(false);
                            track.setDownloadUrl("");
                            track.type = "radio";
                            track.setSubordinatedAlbum(subordinatedAlbum);
                            track.setAnnouncer(announcer);
                            track.setLive(true);
                            sources.add(track);
                        }
                        AlbumRadioAudioPlayer.get().setOnSources(sources, sources.size() - 1, 4, -1);

                    }
                });


            }

        } catch (SQLException e) {
            e.printStackTrace();
        }
    }


    private HashMap<Long, List<DownloadTrackDbBean>> groupBys
            (List<DownloadTrackDbBean> lists) {
        HashMap<Long, List<DownloadTrackDbBean>> map = new HashMap<Long, List<DownloadTrackDbBean>>();
        Long key_str = -1L;
        List<DownloadTrackDbBean> value_list;
        /*** 将list分组，存入map ***/
        for (DownloadTrackDbBean cycleData : lists) {
            key_str = cycleData.getAlbumId();
            value_list = new ArrayList<>();
            if (key_str != -1) {
                if (map.containsKey(key_str)) {
                    value_list = (List) map.get(key_str);
                }
                value_list.add(cycleData);
                map.put(key_str, value_list);
            }
        }
        return map;
    }


    private void SyncFav() {

    }

    public class PlayBinder extends Binder {
        public PlayAlbumRadioService getService() {
            return PlayAlbumRadioService.this;
        }
    }


    /**
     * @param radio
     */
    private void doGetNextDownload(RecentAlbumRadioTrackBean radio) {
        HashMap<String, Object> queryMaps = new HashMap<>();
        queryMaps.put("userId", MusicApplication.GetUserId());
        try {
            helper.getDownloadDao().queryBuilder().where().eq("userId", MusicApplication.GetUserId()).query();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    private Handler delayHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (PreferenceUtils.GetRadioPlayingStatus()) {
                Intent intent = new Intent(PlayAlbumRadioService.this, MainActivity.class);
                startActivity(intent);
            }
        }
    };


    private void initLoginStatus() {
//        managerServiceConnectionListener = new VehicleInfoHelper.ManagerServiceConnectionListener() {
//            @Override
//            public void onManagerServiceConnect() {
//                try {
//                    boolean isServiceOn = OnlineServiceManager.getInstance(PlayAlbumRadioService.this).isOnlineServiceOn();
//                    CnsAccountInfo accountInfo = CnsAccountManager.getInstance(PlayAlbumRadioService.this).getAccountInfo();
//                    Logger.i("account type-->" + accountInfo.getType());
//                    boolean isLogin = !(accountInfo.getType() == 2 || accountInfo.getType() == 3);
//                    Logger.i("PlayAlbumRadioService ServiceOn-->" + isServiceOn);
//                    Logger.i("PlayAlbumRadioService isLogin-->" + isLogin);
//
//                    if ((!isLogin) || (!isServiceOn)) {
//                        if (AlbumRadioAudioPlayer.get().isPlaying()) {
//                            Constants.FLAG_PAUSE_MANUAL = true;
//                            Constants.FLAG_FOCUS_ON_SELF = false;
//                        }
//                        AlbumRadioAudioPlayer.get().playPauseAbandonFocus();
//                    }
//                } catch (RemoteException e) {
//                }
//            }
//
//            @Override
//            public void onManagerServiceDisconnection() {
//                if (AlbumRadioAudioPlayer.get().isPlaying()) {
//                    Constants.FLAG_PAUSE_MANUAL = true;
//                    Constants.FLAG_FOCUS_ON_SELF = false;
//                }
//                AlbumRadioAudioPlayer.get().playPauseAbandonFocus();
//            }
//        };
//        if (Constants.isRelease) {
////            CnsAccountManager.getInstance(this).registerManagerServiceConnection(managerServiceConnectionListener);
//        }
    }


    private void initAccountStatus() {
        IntentFilter filter = new IntentFilter(CustomIntent.ACTION_SVW_ACCOUNT_CHANGED);
        IntentFilter filterToken = new IntentFilter(CustomIntent.ACTION_SVW_TOKEN_CHANGED);
        IntentFilter filterOnlineService = new IntentFilter(CustomIntent.ACTION_ONLINESERVICE_STATE);


        this.changeAccountReiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
//                Logger.i("change vw account");
//                CnsAccountManager.getInstance(PlayAlbumRadioService.this).unregisterManagerServiceConnection(managerServiceConnectionListener);
//                initLoginStatus();
            }
        };

        this.tokenChangeReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
//                Logger.i("change vw token");
//                CnsAccountManager.getInstance(PlayAlbumRadioService.this).unregisterManagerServiceConnection(managerServiceConnectionListener);
//                initLoginStatus();
            }
        };
        this.onlineServiceChangeReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
//                Logger.i("change onlineService status");
//                CnsAccountManager.getInstance(PlayAlbumRadioService.this).unregisterManagerServiceConnection(managerServiceConnectionListener);
//                initLoginStatus();
            }
        };
        if (Constants.isRelease) {
//            this.registerReceiver(changeAccountReiver, filter);
//            this.registerReceiver(tokenChangeReceiver, filterToken);
//            this.registerReceiver(onlineServiceChangeReceiver,filterOnlineService);
        }
    }


    private Handler delaySetInitDataFlagHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            Logger.i("delaySetInitDataFlagHandler-->");
            Constants.NeedInitDataFlag = false;
        }
    };


    private VehicleInfoHelper.ManagerServiceConnectionListener accountListener;

    private void initAccountListener() {
        accountListener = new VehicleInfoHelper.ManagerServiceConnectionListener() {
            @Override
            public void onManagerServiceConnect() {
                Logger.i("initAccountListener-->onManagerServiceConnect");
                boolean isLogin = false;
                boolean isServiceOn = false;
                try {
                    if (CnsAccountManager.getInstance(PlayAlbumRadioService.this).getAccountInfo() == null) {
                        Logger.i("onlineServiceOn-->account info is null");
                    } else {
                        CnsAccountInfo accountInfo = CnsAccountManager.getInstance(PlayAlbumRadioService.this).getAccountInfo();
                        Logger.i("accountInfo-->" + new Gson().toJson(accountInfo));
                        Constants.USER_TYPE = accountInfo.getType();
                        isLogin = !(accountInfo.getType() == 2 || accountInfo.getType() == 3);
                        isServiceOn = OnlineServiceManager.getInstance(PlayAlbumRadioService.this).isOnlineServiceOn();
                        AppTokenInfo tokenInfo = AppTokenManager.getInstance(PlayAlbumRadioService.this).getAuthToken("mos_radio_service_v1");
                        boolean isToken = false;
                        if (tokenInfo == null) {
                            Logger.i("token is null true");
                        } else {
                            Logger.i("token--->" + new Gson().toJson(tokenInfo));
                        }
                        if (tokenInfo != null && (!TextUtils.isEmpty(tokenInfo.getToken()))) {
                            isToken = true;
                            Logger.i("Service Token-->" + new Gson().toJson(tokenInfo));
                            PreferenceUtils.SaveTokenInfo(tokenInfo);
                        }
                        Logger.i("isLogin-->" + isLogin);
                        Logger.i("isServiceOn-->" + isServiceOn);
                        Logger.i("NeedInitDataFlag-->" + Constants.NeedInitDataFlag);
                        Logger.i("Token is not null-->" + isToken);
                        if (isLogin && isServiceOn && Constants.NeedInitDataFlag && isToken) {
                            if (PreferenceUtils.GetRadioPlayingStatus()) {
                                initData();
                                Constants.NeedInitDataFlag = false;
                            }
                        } else if (isLogin && isServiceOn && isToken) {
                            AppTokenInfo appTokenInfo = null;
                            try {
                                appTokenInfo = AppTokenManager.getInstance(PlayAlbumRadioService.this).getAuthToken("mos_radio_service_v1");
                                PreferenceUtils.SaveTokenInfo(appTokenInfo);
                                Logger.i("PlayAlbumRadioService 鉴权 appTokenInfo-->" + PreferenceUtils.GetTokenInfo());
                                CnsAccountInfo accountInfo2 = CnsAccountManager.getInstance(PlayAlbumRadioService.this).getAccountInfo();
                                PreferenceUtils.SaveAccountInfo(accountInfo2);
                                Logger.i("PlayAlbumRadioService 鉴权 accountInfo-->" + PreferenceUtils.GetAccountInfo());
                                String uuid = UUID.randomUUID().toString();
                                String deviceId = VehicleManager.getInstance(PlayAlbumRadioService.this).getHeadunitDeviceId();
                                PreferenceUtils.SaveDeviceId(deviceId);
                                Logger.i("PlayAlbumRadioService 鉴权 deviceId-->" + PreferenceUtils.GetDeviceId());
                                String vinNumber = VehicleManager.getInstance(PlayAlbumRadioService.this).getVINNumber();
                                PreferenceUtils.SaveVinNum(vinNumber);
                                Logger.i("PlayAlbumRadioService 鉴权 vinNumber-->" + PreferenceUtils.GetVinNum());
                            } catch (RemoteException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                } catch (RemoteException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onManagerServiceDisconnection() {

            }
        };
        CnsAccountManager.getInstance(this).registerManagerServiceConnection(accountListener);
        IntentFilter filter = new IntentFilter(CustomIntent.ACTION_SVW_ACCOUNT_CHANGED);
        this.changeAccountReiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                Logger.i("change vw account");
                CnsAccountManager.getInstance(PlayAlbumRadioService.this).unregisterManagerServiceConnection(accountListener);
                CnsAccountManager.getInstance(PlayAlbumRadioService.this).registerManagerServiceConnection(accountListener);
            }
        };
        IntentFilter filterToken = new IntentFilter(CustomIntent.ACTION_SVW_TOKEN_CHANGED);
        this.tokenChangeReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                Logger.i("change vw token");
                CnsAccountManager.getInstance(PlayAlbumRadioService.this).unregisterManagerServiceConnection(accountListener);
                CnsAccountManager.getInstance(PlayAlbumRadioService.this).registerManagerServiceConnection(accountListener);
            }
        };
        this.registerReceiver(changeAccountReiver, filter);
        this.registerReceiver(tokenChangeReceiver, filterToken);
    }

    @Override
    public void onCreate() {
        super.onCreate();
        radioModel = new RadioImpl();
        Logger.i("onCreate()-->enter Service启动");
        Log.i(TAG, "onCreate: " + getClass().getSimpleName());
        AlbumRadioAudioPlayer.get().init(this);
//        AlbumRadioAudioPlayer.get().play();
//        getAlbumTrack();
        AlbumRadioAudioPlayer.get().addOnPlayEventListener(this);


        AlbumMediaSessionManager.get().init(this);
        proxy = MusicApplication.getProxy(this);
        if (Build.VERSION.SDK_INT >= 26) {


            String CHANNEL_ID = "com.jpcc.vw.onlineRadio.service.PlayAlbumRadioService";
            String CHANNEL_NAME = "PlayAlbumRadioService";
            NotificationChannel channel = new NotificationChannel(CHANNEL_ID, CHANNEL_NAME, NotificationManager.IMPORTANCE_LOW);
            NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
            manager.createNotificationChannel(channel);
            startForeground(0x999, new Notification.Builder(this, CHANNEL_ID).build());


        } else {
            Notification.Builder builder = new Notification.Builder(this);
            builder.setSmallIcon(R.drawable.radio);
            builder.setContentTitle("Radio");
            builder.setContentText("Radio is runing...");
            startForeground(0x999, builder.build());
        }


//        Logger.i("lastMode-->" + Constants.NeedInitDataFlag);
        Logger.i("GetFrontStatus-->" + PreferenceUtils.GetFrontStatus());
        if (Constants.NeedInitDataFlag) {
            Logger.i("initData-->initData()");
            Logger.i("playing status-->" + PreferenceUtils.GetRadioPlayingStatus());
            if (PreferenceUtils.GetRadioPlayingStatus()) {
                Logger.i("Size-->" + MusicApplication.GetInstance().getActivityNum());
                if (MusicApplication.GetInstance().getActivityNum() <= 0 && Constants.LastModeFlag) {
                    if (PreferenceUtils.GetFrontStatus()) {
                        Intent intent = new Intent(PlayAlbumRadioService.this, MainActivity.class);
                        startActivity(intent);
                    }
                }
                //为了LastMode
                if (!Constants.isRelease) {
                    initData();
                }
            }
            //为了LastMode
            //Constants.NeedInitDataFlag = false;
        }

        //为了lastMode
        if (Constants.isRelease) {
            initAccountListener();
        }


        if (MusicApplication.GetInstance().getActivityNum() <= 0) {
            Logger.i("GetFrontStatus-->" + PreferenceUtils.GetFrontStatus());
            Logger.i("PlayingStatus-->" + PreferenceUtils.GetRadioPlayingStatus());
//            if (PreferenceUtils.GetFrontStatus() && PreferenceUtils.GetRadioPlayingStatus()) {

//            if (PreferenceUtils.GetRadioPlayingStatus()) {
////                Intent intent = new Intent(this, MainActivity.class);
////                startActivity(intent);
//
//            }
//            delayHandler.sendEmptyMessageDelayed(0x09,800);
        } else {
            Constants.LastModeFlag = false;
        }

        if (MusicApplication.GetInstance().getActivityNum() > 0) {
        }

        IntentFilter filter = new IntentFilter();
        filter.addAction(CustomIntent.ACTION_SDS_COMMAND);
        SDSReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                Logger.i("sds_radio", "extra_command:" + intent.getStringExtra(CustomIntent.EXTRA_COMMAND));
                Logger.i("sds_radio", "extra_request_id:" + intent.getStringExtra(CustomIntent.EXTRA_REQUEST_ID));
                dealSDSCommand(intent.getStringExtra(CustomIntent.EXTRA_COMMAND), intent.getStringExtra(CustomIntent.EXTRA_REQUEST_ID));
            }
        };
//        this.registerReceiver(SDSReceiver, filter);
        IntentFilter controlFilter = new IntentFilter("android.intent.action.MEDIA_BUTTON");
        remoteControlReceiver = new RemoteControlReceiver();
        EventBus.getDefault().register(this);
        initLoginStatus();
        popReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                if (intent != null) {
                    if (intent.getAction().equals("com.jpcc.vw.PlayAlbumRadioService")) {
                        Bundle bundle = intent.getExtras();
                        if (bundle != null) {
                            if ("PayForTrack".equals(bundle.getString("action"))) {
                                boolean isBoughtByAlbum = bundle.getBoolean("isBoughtByAlbum");
                                String PriceTypeInfoBeanString = bundle.getString("PriceTypeInfoBean");
                                PriceTypeInfoBean response = new Gson().fromJson(PriceTypeInfoBeanString, PriceTypeInfoBean.class);
                                long Id = bundle.getLong("Id");
                                long trackId = bundle.getLong("trackId");
                                Logger.i("pop value isBoughtByAlbum-->" + isBoughtByAlbum);
                                Logger.i("pop value PriceTypeInfoBeanString-->" + PriceTypeInfoBeanString);
                                Logger.i("pop value Id-->" + Id);
                                Logger.i("pop value trackId-->" + trackId);
                                placeOrder(isBoughtByAlbum, response, Id, trackId);
                            } else if ("PayForVIP".equals(bundle.getString("action"))) {
                                Intent intentPersonal = PlayAlbumRadioService.this.getPackageManager().getLaunchIntentForPackage("com.jpcc.vw.personalcenter");
                                intentPersonal.putExtra("mediaType", 1);
                                intentPersonal.putExtra("jumpType", 2);
                                intentPersonal.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                                startActivity(intentPersonal);
                            }
                        }
                    }
                }
            }
        };
        IntentFilter filterPop = new IntentFilter();
        filterPop.addAction("com.jpcc.vw.PlayAlbumRadioService");
        this.registerReceiver(popReceiver, filterPop);
        payResultReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                String paiedStatus = intent.getStringExtra("payResult");
                Logger.i("paiedStatus-->" + paiedStatus);
                if ("101".equals(paiedStatus)) {
                    String paiedFlag = intent.getStringExtra("payOrderCategory");
                    Logger.i("paiedFlag-->" + paiedFlag);
                    if ("07".equals(paiedFlag)) {
                        if (isBoughtByAlbum) {
                            List<Track> tracks = new ArrayList<>();
                            tracks.addAll(AlbumRadioAudioPlayer.get().getTracks());
                            int index = 0;
                            for (Track track : tracks) {
                                track.setIs_paid(true);
                                track.setIs_authorized(true);
                            }
                            for (int position = 0; position < tracks.size(); position++) {
                                if (AlbumRadioAudioPlayer.get().getPlayMusic().getTrackId() == tracks.get(position).getId()) {
                                    index = position;
                                }
                            }
                            AlbumRadioAudioPlayer.get().setOnSources(tracks, index, 4, 0);
                        } else {
                            List<Track> tracks = new ArrayList<>();
                            tracks.addAll(AlbumRadioAudioPlayer.get().getTracks());
                            int index = 0;
                            for (int position = 0; position < tracks.size(); position++) {
                                if (AlbumRadioAudioPlayer.get().getPlayMusic().getTrackId() == tracks.get(position).getId()) {
                                    index = position;
                                    tracks.get(position).setIs_paid(true);
                                    tracks.get(position).setIs_authorized(true);
                                }
                            }
                            AlbumRadioAudioPlayer.get().setOnSources(tracks, index, 4, 0);
                        }
                    } else if ("02".equals(paiedFlag)) {
                        PreferenceUtils.SaveVIPStatus(true);
                        List<Track> tracks = new ArrayList<>();
                        tracks.addAll(AlbumRadioAudioPlayer.get().getTracks());
                        int index = 0;
                        for (int position = 0; position < tracks.size(); position++) {
                            if (AlbumRadioAudioPlayer.get().getPlayMusic().getTrackId() == tracks.get(position).getId()) {
                                index = position;
                            }
                        }
                        AlbumRadioAudioPlayer.get().setOnSources(tracks, index, 4, 0);
                    }
                }
            }
        };
        IntentFilter filterPayResult = new IntentFilter("com.jpcc.vw.payment.constants.pay.result");
        this.registerReceiver(payResultReceiver, filterPayResult);
    }


    public void onEvent(StartPlayerAction action) {
        if (initStart) {
            initStart = false;
        }
    }

    private boolean isBoughtByAlbum = false;

    private void placeOrder(boolean isBoughtByAlbum, PriceTypeInfoBean priceTypeInfo, long Id, long trackId) {
        this.isBoughtByAlbum = isBoughtByAlbum;
        PlaceOrderBean order = new PlaceOrderBean();
        order.setPriceType(priceTypeInfo.getData().getPriceTypeDetail().get(0).getPriceType());
        order.setPrice(priceTypeInfo.getData().getPriceTypeDetail().get(0).getDiscountedPrice() + "");
        order.setPayContent(Id);

        String vin = "";
        if (!TextUtils.isEmpty(PreferenceUtils.GetVinNum())) {
            Logger.i("vin-->" + PreferenceUtils.GetVinNum());
            vin = PreferenceUtils.GetVinNum();
        } else {
            File configFile = new File("/mnt/nfs/onlineapplication.conf");
            if (configFile.exists()) {
                String vinConfig = ConfigReaderUtils.readVidFromConfig();
                Logger.i("vinConfig-->" + vinConfig);
                vin = vinConfig;
            }
        }

        if (TextUtils.isEmpty(vin)) {
            vin = "LGVIN001000000001";
        }


        order.setVin(vin);


        Logger.i("vinCode-->" + vin);

        boolean finalIsBoughtByAlbum = isBoughtByAlbum;
        HttpClient.PlaceOrder(new Gson().toJson(order), new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                Logger.i("PlaceOrder response onError-->" + e.toString());
            }

            @Override
            public void onResponse(String response, int id) {
                ToastUtils.show("success");
                XiMaLaYaOrderBean result = new Gson().fromJson(response, XiMaLaYaOrderBean.class);
                Logger.i("PlaceOrder response-->" + response);
                if (result.getCode() == 0) {
                    Logger.i("OrderNo-->" + result.getData().getOrderNo());
                    PaySdk.getInstance().pay(PlayAlbumRadioService.this, result.getData().getOrderNo() + "", order.getPrice(), "101", new NewPayResultListener() {
                        @Override
                        public void onPaySuccess(String s) {
                        }

                        @Override
                        public void onPayFailed(String s) {

                        }
                    });
                } else {
                    ToastUtils.show(result.getStatusMessage());
                }
            }
        });
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        Logger.i("service destory");
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
//        this.unregisterReceiver(SDSReceiver);
//        this.unregisterReceiver(remoteControlReceiver);
//        this.unregisterReceiver(networkChangeReceiver);
    }


    /**
     * 同步数据  包括fav数据以及history数据
     */
    private void syncData() {

        RecentAlbumRadioTrackBean lastMode = null;
        if (TextUtils.isEmpty(PreferenceUtils.GetUserLastMode())) {
            lastMode = null;
        } else {
            lastMode = new Gson().fromJson(PreferenceUtils.GetUserLastMode(), RecentAlbumRadioTrackBean.class);
        }


        RecentAlbumRadioTrackBean finalLastMode = lastMode;
        SyncFavUtils.syncFav(this, new SyncFavUtils.onSyncFav() {
            @Override
            public void onSyncFavSuccess() {
                boolean flag = false;
                if (finalLastMode == null) {
                    flag = false;
                } else {
                    flag = finalLastMode.getFrom() == 0;
                }
                getLastFavDataToDatabase(flag);
            }

            @Override
            public void onsyncFavFail() {

            }
        });
    }


    private void getLastFavDataToDatabase(boolean flag) {

        /*Start by menglingqiang*/
        Date dt = new Date();
        try {
            TracelogInterface inter = MusicApplication.getLogInterface();
            if (inter != null) {
                inter.sendLogData(dt.toString(), dt.toString(), PlayAlbumRadioService.this.getClass().getName(), "DEBUG", "400", "GetAlbumRadioFavourite Request");
            } else {
                Log.e("JPCC", "inter == null");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        /*End by menglingqiang*/

        radioModel.GetAlbumRadioFavourite().doOnSubscribe(new Action0() {
            @Override
            public void call() {
            }
        }).subscribe(new CommonSubscriber<AlbumFavouriteBean>() {
            @Override
            public void onSuccess(AlbumFavouriteBean response) {
                List<CommonFavouritePaiedHistoryEntity> local_datas = new ArrayList<>();
                local_datas.addAll(response.getDataALL());
                saveDbFav(response.getDataALL());
                if (flag) {
                    RecentAlbumRadioTrackBean lastMode = new Gson().fromJson(PreferenceUtils.GetUserLastMode(), RecentAlbumRadioTrackBean.class);
                    initFavAlbumData(lastMode);
                }

                /*Start by menglingqiang*/
                Date dt = new Date();
                try {
                    TracelogInterface inter = MusicApplication.getLogInterface();
                    if (inter != null) {
                        inter.sendLogData(dt.toString(), dt.toString(), PlayAlbumRadioService.this.getClass().getName(), "DEBUG", "400", "GetAlbumRadioFavourite onSuccess");
                    } else {
                        Log.e("JPCC", "inter == null");
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                /*End by menglingqiang*/
            }

            @Override
            public void onFailure(BaseBean response) {
                ToastUtils.show(response.getStatusMessage());
                /*Start by menglingqiang*/
                Date dt = new Date();
                try {
                    TracelogInterface inter = MusicApplication.getLogInterface();
                    if (inter != null) {
                        inter.sendLogData(dt.toString(), dt.toString(), PlayAlbumRadioService.this.getClass().getName(), "ERROR", "400", "GetAlbumRadioFavourite onSuccess");
                    } else {
                        Log.e("JPCC", "inter == null");
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                /*End by menglingqiang*/
            }
        });
    }


    private void saveDbFav(List<CommonFavouritePaiedHistoryEntity> sources) {
        if (sources != null) {
            for (CommonFavouritePaiedHistoryEntity entity : sources) {
                DatabaseHelperOrm helper = DatabaseHelperOrm.getHelper(this);
                try {
                    Dao dao = helper.getFavouriteDao();
                    dao.create(CommonFavouritePaiedHistoryEntity2FavouriteAlbumDbBean(entity));
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
    }


    private void saveDbHistory(List<PlayHistoryEntity> sources) {
        DeleteBuilder deleteBuilder = null;
        try {
            deleteBuilder = helper.getRecentDao().deleteBuilder();
            deleteBuilder.where().eq("userId", MusicApplication.GetUserId());
            deleteBuilder.delete();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        if (sources != null) {
            for (PlayHistoryEntity entity : sources) {
                RecentAlbumRadioTrackBean bean = new RecentAlbumRadioTrackBean();
                if (entity.getContentType() == 1) {
                    bean.setType("album");
                    bean.setAlbumId(entity.getAlbumId());
                    bean.setTrackId(entity.getTrackId());
                    bean.setAlbumName(entity.getAlbumTitle());
                    bean.setTrackName(entity.getTrackTitle());
                    bean.setTimeStamp(entity.getPlayBeginAt());
//                    bean.setCurrentDuration((int) entity.getBreakSecond() * 1000);
                    bean.setCover(entity.getTrackCoverUrlLarge());
                } else {
                    bean.setType("radio");
                    bean.setAlbumId(entity.getRadioId());
                    bean.setTrackId(-999);
                    bean.setAlbumName(entity.getRadioName());
                    bean.setTrackName("");
                    bean.setTimeStamp(entity.getPlayBeginAt());
                    bean.setCurrentDuration(0);
                    bean.setCover(entity.getTrackCoverUrlLarge());
                }
                try {
                    helper.getRecentDao().create(bean);
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    private FavouriteAlbumDbBean CommonFavouritePaiedHistoryEntity2FavouriteAlbumDbBean
            (CommonFavouritePaiedHistoryEntity input) {
        FavouriteAlbumDbBean out = new FavouriteAlbumDbBean();
        out.setContentAbstract(input.getContentAbstract());
        out.setCoverUrlLarge(input.getCoverUrlLarge());
//        out.setCoverUrlMiddle(input.getCoverUrlMiddle());
//        out.setCoverUrlSmall(input.getCoverUrlSmall());
        out.setCpSource(input.getCpSource());
        out.setHostName(input.getHostName());
        out.setId(input.getId());
        out.setName(input.getName());
        out.setType(input.getType());
        out.setUserId(MusicApplication.GetUserId());
        return out;
    }

    private Handler delayInitRadio = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            String jsonLastTrack = (String) msg.obj;
            Logger.i("handleMesssage-->" + jsonLastTrack);
            RecentAlbumRadioTrackBean lastTrack = new Gson().fromJson(jsonLastTrack, RecentAlbumRadioTrackBean.class);
            initFavRadioData(lastTrack);
        }
    };


    /**
     * 重新启动之后
     * 自动播放上一次的播放
     */
    private void initData() {
        Logger.i("enter-->initData()");
        try {
            RecentAlbumRadioTrackBean lastRecent = helper.getRecentDao().queryBuilder().orderBy("timeStamp", false).where().eq("userId", MusicApplication.GetInstance().GetUserId()).queryForFirst();
            List<Track> infosLocal = new ArrayList<>();
            if (!TextUtils.isEmpty(PreferenceUtils.GetLastPlayingJson())) {
                Logger.i("上次收听-->" + PreferenceUtils.GetLastPlayingJson());
                infosLocal = new Gson().fromJson(PreferenceUtils.GetLastPlayingJson(), new TypeToken<List<Track>>() {
                }.getType());
                Logger.i("lastjson is null-->" + (infosLocal == null));
                if (infosLocal != null && infosLocal.size() > 0) {
//                    Logger.i("lastjson from-->" + infos.get(0));
                    Logger.i("lastjson type-->" + infosLocal.get(0).getType());
                    Logger.i("lastjson-->" + new Gson().toJson(infosLocal));
                }
            } else {
                Logger.i("上次收听为空");
            }
            if (lastRecent != null) {
                Logger.i("lastRecent is null-->" + (lastRecent == null));
                Logger.i("lastRecent from-->" + lastRecent.getFrom());
                Logger.i("lastRecent type-->" + lastRecent.getType());
                Logger.i("lastRecent-->" + new Gson().toJson(lastRecent));
            }
            Logger.i("infosLocal()-->" + new Gson().toJson(infosLocal));
            if (infosLocal != null && infosLocal.size() > 0) {
                if ("album".equals(infosLocal.get(0).getType())) {
                    List<Track> infos = new Gson().fromJson(PreferenceUtils.GetLastPlayingJson(), new TypeToken<List<Track>>() {
                    }.getType());
                    if (infos != null) {
                        Logger.i("lastJson0-->" + PreferenceUtils.GetLastPlayingJson());
                    }

                    if (TextUtils.isEmpty(PreferenceUtils.GetUserLastMode())) {
                        return;
                    }
                    RecentAlbumRadioTrackBean lastTrack = new Gson().fromJson(PreferenceUtils.GetUserLastMode(), RecentAlbumRadioTrackBean.class);
                    if (lastTrack == null) {
                        return;
                    }
                    if (infos != null && infos.size() > 0) {
                        for (int index = 0; index < infos.size(); index++) {
                            if (infos.get(index).getId() == lastTrack.getTrackId()) {
                                AlbumRadioAudioPlayer.get().setOnSources(infos, index, 0, lastTrack.getCurrentDuration());
                                break;
                            }
                        }
                    }
                } else if ("radio".equals(infosLocal.get(0).getType())) {


                    List<Track> infos = new Gson().fromJson(PreferenceUtils.GetLastPlayingJson(), new TypeToken<List<Track>>() {
                    }.getType());
                    Logger.i("infos is null-->" + (infos == null));
                    if (infos != null) {
                        Logger.i("lastJson1-->" + PreferenceUtils.GetLastPlayingJson());
                    }
                    Logger.i("Radio Last Mode-->" + PreferenceUtils.GetUserLastMode());
                    if (TextUtils.isEmpty(PreferenceUtils.GetUserLastMode())) {
                        return;
                    }
                    RecentAlbumRadioTrackBean lastTrack = new Gson().fromJson(PreferenceUtils.GetUserLastMode(), RecentAlbumRadioTrackBean.class);

                    if (lastTrack == null) {
                        return;
                    }

                    String jsonLastTrack = new Gson().toJson(lastTrack);


                    Message message = Message.obtain();
                    message.obj = jsonLastTrack;


                    delayInitRadio.sendMessageDelayed(message, 5000);
//                    initFavRadioData(lastTrack);
                }
            } else {

            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }


    private void initCommonData(RecentAlbumRadioTrackBean lastRecent) {

        /*Start by menglingqiang*/
        Date dt = new Date();
        try {
            TracelogInterface inter = MusicApplication.getLogInterface();
            if (inter != null) {
                inter.sendLogData(dt.toString(), dt.toString(), PlayAlbumRadioService.this.getClass().getName(), "DEBUG", "400", "GetAlbumBrowse Request");
            } else {
                Log.e("JPCC", "inter == null");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        /*End by menglingqiang*/

        radioModel.GetAlbumBrowse(lastRecent.getAlbumId(), 1).doOnSubscribe(new Action0() {
            @Override
            public void call() {
            }
        }).subscribe(new CommonSubscriber<AlbumBrowseBean>() {
            @Override
            public void onSuccess(AlbumBrowseBean response) {
                List<Track> datas = new ArrayList<>();
                if ((response.getData().getTracks() != null) && (response.getData().getTracks().size() > 0)) {
                    datas.addAll(response.getData().getTracks());
                    for (Track track : datas) {
                        track.setTrackIntro(response.getData().getAlbumIntro());
                    }
                    int position = -1;
                    if (datas != null && datas.size() > 0) {
                        for (int index = 0; index < datas.size(); index++) {
                            if (datas.get(index).getId() == lastRecent.getTrackId()) {
                                position = index;
                            }
                        }
                    }
                    if (position == -1) {
                        return;
                    }
                    AlbumRadioAudioPlayer.get().setOnSources(datas, position, 4, lastRecent.getCurrentDuration());
                }
                /*Start by menglingqiang*/
                Date dt = new Date();
                try {
                    TracelogInterface inter = MusicApplication.getLogInterface();
                    if (inter != null) {
                        inter.sendLogData(dt.toString(), dt.toString(), PlayAlbumRadioService.this.getClass().getName(), "DEBUG", "400", "GetAlbumBrowse onSuccess");
                    } else {
                        Log.e("JPCC", "inter == null");
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                /*End by menglingqiang*/
            }

            @Override
            public void onFailure(BaseBean response) {
                /*Start by menglingqiang*/
                Date dt = new Date();
                try {
                    TracelogInterface inter = MusicApplication.getLogInterface();
                    if (inter != null) {
                        inter.sendLogData(dt.toString(), dt.toString(), PlayAlbumRadioService.this.getClass().getName(), "ERROR", "400", "GetAlbumBrowse onFailure");
                    } else {
                        Log.e("JPCC", "inter == null");
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                /*End by menglingqiang*/
            }
        });
    }


    private void initHistoryData(RecentAlbumRadioTrackBean lastRecent) {
        if (lastRecent != null && "radio".equals(lastRecent.getType())) {

            /*Start by menglingqiang*/
            Date dt = new Date();
            try {
                TracelogInterface inter = MusicApplication.getLogInterface();
                if (inter != null) {
                    inter.sendLogData(dt.toString(), dt.toString(), PlayAlbumRadioService.this.getClass().getName(), "DEBUG", "400", "GetPlayingProgramDetail Request");
                } else {
                    Log.e("JPCC", "inter == null");
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            /*End by menglingqiang*/

            radioModel.GetPlayingProgramDetail(lastRecent.getAlbumId()).doOnSubscribe(new Action0() {
                @Override
                public void call() {
                }
            }).subscribe(new CommonSubscriber<LiveRadioDetailBean>() {
                @Override
                public void onSuccess(LiveRadioDetailBean response) {
                    Track track = new Track();
                    SubordinatedAlbum subordinatedAlbum = new SubordinatedAlbum();
                    subordinatedAlbum.setId(lastRecent.getAlbumId());
                    subordinatedAlbum.setAlbumTitle(lastRecent.getAlbumName());
                    Announcer announcer = new Announcer();
//                    announcer.setNickname(response.getData().getLiveAnnouncers().get(0).getNickname());
                    track.setId(response.getData().getId());
                    track.setTrackTitle(response.getData().getProgramName());
                    track.setCoverUrlLarge(response.getData().getBackPicUrl());
                    track.setPlayUrl32(response.getData().getRate24AacUrl());//response.getData().getSupportBitrates().get(0).getRate24AacUrl());
                    track.setCanDownload(false);
                    track.setDownloadUrl("");
                    track.type = "radio";
                    track.setSubordinatedAlbum(subordinatedAlbum);
                    track.setAnnouncer(announcer);
                    List<Track> sources = new ArrayList<>();
                    sources.add(track);
                    AlbumRadioAudioPlayer.get().setOnSources(sources, 0, 3, lastRecent.getCurrentDuration());
                    /*Start by menglingqiang*/
                    Date dt = new Date();
                    try {
                        TracelogInterface inter = MusicApplication.getLogInterface();
                        if (inter != null) {
                            inter.sendLogData(dt.toString(), dt.toString(), PlayAlbumRadioService.this.getClass().getName(), "DEBUG", "400", "GetPlayingProgramDetail onSuccess");
                        } else {
                            Log.e("JPCC", "inter == null");
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    /*End by menglingqiang*/
                }

                @Override
                public void onFailure(BaseBean response) {
                    ToastUtils.show(response.getStatusMessage());
                    /*Start by menglingqiang*/
                    Date dt = new Date();
                    try {
                        TracelogInterface inter = MusicApplication.getLogInterface();
                        if (inter != null) {
                            inter.sendLogData(dt.toString(), dt.toString(), PlayAlbumRadioService.this.getClass().getName(), "ERROR", "400", "GetPlayingProgramDetail onFailure");
                        } else {
                            Log.e("JPCC", "inter == null");
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    /*End by menglingqiang*/
                }
            });
        } else if (lastRecent != null && "album".equals(lastRecent.getType())) {
            List<Track> infos = new Gson().fromJson(PreferenceUtils.GetLastPlayingJson(), new TypeToken<List<Track>>() {
            }.getType());
            if (infos != null && infos.size() > 0) {
                for (int index = 0; index < infos.size(); index++) {
                    if (infos.get(index).getId() == lastRecent.getTrackId()) {
                        AlbumRadioAudioPlayer.get().setOnSources(infos, index, 3, lastRecent.getCurrentDuration());
                        break;
                    }
                }
            }
        }
    }


    private void initPaiedData(RecentAlbumRadioTrackBean lastRecent) {
        List<Track> datas = new ArrayList<>();

        /*Start by menglingqiang*/
        Date dt = new Date();
        try {
            TracelogInterface inter = MusicApplication.getLogInterface();
            if (inter != null) {
                inter.sendLogData(dt.toString(), dt.toString(), PlayAlbumRadioService.this.getClass().getName(), "DEBUG", "400", "GetAlbumBrowse Request");
            } else {
                Log.e("JPCC", "inter == null");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        /*End by menglingqiang*/

        radioModel.GetAlbumBrowse(lastRecent.getAlbumId(), 1).doOnSubscribe(new Action0() {
            @Override
            public void call() {
            }
        }).subscribe(new CommonSubscriber<AlbumBrowseBean>() {
            @Override
            public void onSuccess(AlbumBrowseBean response) {
                if ((response.getData().getTracks() != null) && (response.getData().getTracks().size() > 0)) {
                    datas.addAll(response.getData().getTracks());
                    for (Track track : datas) {
                        track.setTrackIntro(response.getData().getAlbumIntro());
                    }
                    if (datas.size() > 0) {
                        int position = -1;
                        for (int index = 0; index < datas.size(); index++) {
                            if (datas.get(index).getId() == lastRecent.getTrackId()) {
                                position = index;
                            }
                        }
                        if (position == -1) {
                            return;
                        }
                        AlbumRadioAudioPlayer.get().setOnSources(datas, position, 4, lastRecent.getCurrentDuration());
                    }
                }
                /*Start by menglingqiang*/
                Date dt = new Date();
                try {
                    TracelogInterface inter = MusicApplication.getLogInterface();
                    if (inter != null) {
                        inter.sendLogData(dt.toString(), dt.toString(), PlayAlbumRadioService.this.getClass().getName(), "DEBUG", "400", "GetAlbumBrowse onSuccess");
                    } else {
                        Log.e("JPCC", "inter == null");
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                /*End by menglingqiang*/
            }

            @Override
            public void onFailure(BaseBean response) {
                /*Start by menglingqiang*/
                Date dt = new Date();
                try {
                    TracelogInterface inter = MusicApplication.getLogInterface();
                    if (inter != null) {
                        inter.sendLogData(dt.toString(), dt.toString(), PlayAlbumRadioService.this.getClass().getName(), "ERROR", "400", "GetAlbumBrowse onFailure");
                    } else {
                        Log.e("JPCC", "inter == null");
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                /*End by menglingqiang*/
            }
        });
    }


    private void initDownloadData(RecentAlbumRadioTrackBean lastRecent) {
        List<DownloadTrackDbBean> datas = new ArrayList<>();
        try {
            datas.addAll(helper.getDownloadDao().queryBuilder().where().eq("albumId", lastRecent.getAlbumId()).and().eq("userId", MusicApplication.GetUserId()).query());
            List<Track> infos = new ArrayList<>();
            for (DownloadTrackDbBean db : datas) {
                Track track = new Track();
                SubordinatedAlbum subordinatedAlbum = new SubordinatedAlbum();
                subordinatedAlbum.setId(db.getAlbumId());
                subordinatedAlbum.setAlbumTitle(db.getAlbumName());
                Announcer announcer = new Announcer();
                announcer.setNickname(db.getAuthor());
                track.setId(db.getTrackId());
                track.setTrackTitle(db.getTrackName());
                track.setCoverUrlLarge(db.getCover());
                track.setPlayUrl32(db.getTrackUrl());
                track.setCanDownload(false);
                track.setDownloadUrl("");
                track.type = "album";
                track.setAnnouncer(announcer);
                track.setSubordinatedAlbum(subordinatedAlbum);
                track.setDuration(db.getDuration() / 1000);
                infos.add(track);
            }
            int position = -1;
            for (int index = 0; index < datas.size(); index++) {
                if (datas.get(index).getTrackId() == lastRecent.getTrackId()) {
                    position = index;
                }
            }
            if (position == -1) {
                return;
            }
            AlbumRadioAudioPlayer.get().setOnSources(infos, position, 1, lastRecent.getCurrentDuration());
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }


    private void initFavRadioData(RecentAlbumRadioTrackBean lastRecent) {

        /*Start by menglingqiang*/
        Date dt = new Date();
        try {
            TracelogInterface inter = MusicApplication.getLogInterface();
            if (inter != null) {
                inter.sendLogData(dt.toString(), dt.toString(), PlayAlbumRadioService.this.getClass().getName(), "DEBUG", "400", "GetPlayingProgramDetail Request");
            } else {
                Log.e("JPCC", "inter == null");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        /*End by menglingqiang*/

        if (radioModel == null) {
            radioModel = new RadioImpl();
        }
//        radioModel.GetPlayingProgramDetail(lastRecent.getAlbumId()).doOnSubscribe(new Action0() {
//            @Override
//            public void call() {
//            }
//        }).subscribe(new CommonSubscriber<LiveRadioDetailBean>() {
//            @Override
//            public void onSuccess(LiveRadioDetailBean response) {
//                Track track = new Track();
//                SubordinatedAlbum subordinatedAlbum = new SubordinatedAlbum();
//                subordinatedAlbum.setId(lastRecent.getAlbumId());
//                subordinatedAlbum.setAlbumTitle(lastRecent.getAlbumName());
//                Announcer announcer = new Announcer();
//                track.setId(response.getData().getId());
//                track.setTrackTitle(response.getData().getProgramName());
//                track.setCoverUrlLarge(response.getData().getBackPicUrl());
//                track.setPlayUrl32(response.getData().getRate24AacUrl());//response.getData().getSupportBitrates().get(0).getRate24AacUrl());
//                track.setCanDownload(false);
//                track.setDownloadUrl("");
//                track.type = "radio";
//                track.setLive(true);
//                track.setSubordinatedAlbum(subordinatedAlbum);
//                track.setAnnouncer(announcer);
//                List<Track> sources = new ArrayList<>();
//                sources.add(track);
//                AlbumRadioAudioPlayer.get().setOnSourcesForRadio(sources, track, true, 0);
//                /*Start by menglingqiang*/
//                Date dt = new Date();
//                try {
//                    TracelogInterface inter = MusicApplication.getLogInterface();
//                    if (inter != null) {
//                        inter.sendLogData(dt.toString(), dt.toString(), PlayAlbumRadioService.this.getClass().getName(), "DEBUG", "400", "GetPlayingProgramDetail onSuccess");
//                    } else {
//                        Log.e("JPCC", "inter == null");
//                    }
//                } catch (Exception e) {
//                    e.printStackTrace();
//                }
//                /*End by menglingqiang*/
//            }
//
//            @Override
//            public void onFailure(BaseBean response) {
//                ToastUtils.show(response.getStatusMessage());
//                /*Start by menglingqiang*/
//                Date dt = new Date();
//                try {
//                    TracelogInterface inter = MusicApplication.getLogInterface();
//                    if (inter != null) {
//                        inter.sendLogData(dt.toString(), dt.toString(), PlayAlbumRadioService.this.getClass().getName(), "ERROR", "400", "GetPlayingProgramDetail onFailure");
//                    } else {
//                        Log.e("JPCC", "inter == null");
//                    }
//                } catch (Exception e) {
//                    e.printStackTrace();
//                }
//                /*End by menglingqiang*/
//            }
//        });


        Date today = new Date();
        Calendar c = Calendar.getInstance();
        c.setTime(today);
        int weekday = c.get(Calendar.DAY_OF_WEEK);

        Observable.zip(radioModel.GetPlayingProgramDetail(lastRecent.getAlbumId()), radioModel.getLiveSchedules(lastRecent.getAlbumId(), weekday - 1), new Func2<LiveRadioDetailBean, RadioDeailBean, RadioSumBean>() {
            @Override
            public RadioSumBean call(LiveRadioDetailBean liveRadioDetailBean, RadioDeailBean radioDeailBean) {
                RadioSumBean response = new RadioSumBean();
                if (liveRadioDetailBean.getCode() == 0 && radioDeailBean.getCode() == 0) {
                    response.setLiveRadio(liveRadioDetailBean);
                    response.setRadioSchedule(radioDeailBean);
                    return response;
                }
                return response;
            }
        }).doOnSubscribe(new Action0() {
            @Override
            public void call() {
//                showProgress();
            }
        }).subscribe(new Subscriber<RadioSumBean>() {
            @Override
            public void onCompleted() {
//                hideProgress();
            }

            @Override
            public void onError(Throwable e) {
//                hideProgress();
                Logger.i("request error-->" + e.toString());
            }

            @Override
            public void onNext(RadioSumBean radioSumBean) {
//                hideProgress();
                List<Track> sources = new ArrayList<>();


                if (radioSumBean.getRadioSchedule() != null && radioSumBean.getRadioSchedule().getData() != null) {
                    for (RadioDeailBean.RadioSchedule schedule : radioSumBean.getRadioSchedule().getData()) {
                        if (!TextUtils.isEmpty(schedule.getListenBackUrl())) {
                            Track track = new Track();
                            SubordinatedAlbum subordinatedAlbum = new SubordinatedAlbum();
                            subordinatedAlbum.setId(lastRecent.getAlbumId());
                            subordinatedAlbum.setAlbumTitle(lastRecent.getAlbumName());
                            Announcer announcer = new Announcer();
                            announcer.setNickname("");
                            track.setId(schedule.getId());
                            track.setTrackTitle(schedule.getRelatedProgram().getProgramName());
                            track.setCoverUrlLarge(schedule.getRelatedProgram().getBackPicUrl());
                            track.setPlayUrl32(schedule.getListenBackUrl());
                            track.setCanDownload(false);
                            track.setDownloadUrl("");
                            track.type = "radio";
                            track.setSubordinatedAlbum(subordinatedAlbum);
                            track.setAnnouncer(announcer);
                            track.setLive(false);


                            SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
                            long endInt = 0;
                            long startInt = 0;
                            try {
                                if (schedule.getEndTime().equals("00:00")) {
                                    schedule.setEndTime("24:00");
                                }
                                Date end = sdf.parse(schedule.getEndTime());
                                endInt = end.getTime();
                                Date start = sdf.parse(schedule.getStartTime());
                                startInt = start.getTime();
                                Logger.i("endtime-startTime--->" + (endInt - startInt) / 1000);
                            } catch (ParseException e) {
                                e.printStackTrace();
                            }
                            track.setStartTime(schedule.getStartTime());
                            track.setEndString(schedule.getEndTime());
                            track.setDuration((endInt - startInt) / 1000);
                            sources.add(track);
                        }
                    }
                }


                Track liveRadio = new Track();
                if (radioSumBean.getLiveRadio() != null) {
                    LiveRadioDetailBean response = radioSumBean.getLiveRadio();
                    SubordinatedAlbum subordinatedAlbum = new SubordinatedAlbum();
                    subordinatedAlbum.setId(lastRecent.getAlbumId());
                    subordinatedAlbum.setAlbumTitle(lastRecent.getAlbumName());
                    Announcer announcer = new Announcer();
                    announcer.setNickname("");
                    liveRadio.setId(response.getData().getId());
                    liveRadio.setTrackTitle(response.getData().getProgramName());
                    liveRadio.setCoverUrlLarge(response.getData().getBackPicUrl());
                    liveRadio.setPlayUrl32(response.getData().getRate24AacUrl());
                    liveRadio.setCanDownload(false);
                    liveRadio.setDownloadUrl("");
                    liveRadio.type = "radio";
                    liveRadio.setSubordinatedAlbum(subordinatedAlbum);
                    liveRadio.setAnnouncer(announcer);
                    liveRadio.setLive(true);
                }
//                Constants.LastModeFlag = false;
//                AlbumRadioAudioPlayer.get().setOnSources(sources, 0, 4, -1);
                AlbumRadioAudioPlayer.get().setOnSourcesForRadio(sources, liveRadio, true, 0);
//                localRadioAdapter.notifyDataSetChanged();

            }
        });


    }


    private void initFavAlbumData(RecentAlbumRadioTrackBean lastRecent) {

        /*Start by menglingqiang*/
        Date dt = new Date();
        try {
            TracelogInterface inter = MusicApplication.getLogInterface();
            if (inter != null) {
                inter.sendLogData(dt.toString(), dt.toString(), PlayAlbumRadioService.this.getClass().getName(), "DEBUG", "400", "GetAlbumBrowse Request");
            } else {
                Log.e("JPCC", "inter == null");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        /*End by menglingqiang*/

        radioModel.GetAlbumBrowse(lastRecent.getAlbumId(), 1).subscribe(new CommonSubscriber<AlbumBrowseBean>() {
            @Override
            public void onSuccess(AlbumBrowseBean response) {
                if ((response.getData().getTracks() != null) && (response.getData().getTracks().size() > 0)) {
                    List<Track> datas = new ArrayList<>();
                    datas.addAll(response.getData().getTracks());
                    for (Track track : datas) {
                        track.setTrackIntro(response.getData().getAlbumIntro());
                    }
                    int position = -1;
                    for (int index = 0; index < datas.size(); index++) {
                        if (datas.get(index).getId() == lastRecent.getTrackId()) {
                            position = index;
                        }
                    }
                    if (position < 0) {
                        return;
                    }
                    AlbumRadioAudioPlayer.get().setOnSources(datas, position, lastRecent.getFrom(), lastRecent.getCurrentDuration());
                }
                /*Start by menglingqiang*/
                Date dt = new Date();
                try {
                    TracelogInterface inter = MusicApplication.getLogInterface();
                    if (inter != null) {
                        inter.sendLogData(dt.toString(), dt.toString(), PlayAlbumRadioService.this.getClass().getName(), "DEBUG", "400", "GetAlbumBrowse onSuccess");
                    } else {
                        Log.e("JPCC", "inter == null");
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                /*End by menglingqiang*/
            }

            @Override
            public void onFailure(BaseBean response) {
                /*Start by menglingqiang*/
                Date dt = new Date();
                try {
                    TracelogInterface inter = MusicApplication.getLogInterface();
                    if (inter != null) {
                        inter.sendLogData(dt.toString(), dt.toString(), PlayAlbumRadioService.this.getClass().getName(), "ERROR", "400", "GetAlbumBrowse onFailure");
                    } else {
                        Log.e("JPCC", "inter == null");
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                /*End by menglingqiang*/
            }
        });
    }

    /**
     * 处理来自于SDS的命令
     *
     * @param
     * @param jsonParam
     */
    private void dealSDSCommand(String jsonParam, String requestId) {
        try {
            JSONObject jsonObject = new JSONObject(jsonParam);
            String requestType = jsonObject.getString("requestType");
            Logger.i(requestType);
            String domain = jsonObject.getString("domain");
            if (!"onlineRadio".equals(domain)) {
                return;
            }
            //表示未登陆用户
            if (Constants.USER_TYPE == 3) {

                SDSCommonResult response = new SDSCommonResult();
                SDSCommonOuterResultBean resultOuter = new SDSCommonOuterResultBean();
                resultOuter.setDomain("onlineRadio");
                resultOuter.setRequestType(requestType);
                response.setErrorCode("accountNotLogIn");
                resultOuter.setRequestResult(response);
                try {
                    SDSResponse.getInstance(this).sendResponse(requestId, new Gson().toJson(resultOuter), false);
                } catch (RemoteException e) {
                    e.printStackTrace();
                }
                return;

            }
            //权限不够用户
            if (Constants.USER_TYPE == 2) {

                SDSCommonResult response = new SDSCommonResult();
                SDSCommonOuterResultBean resultOuter = new SDSCommonOuterResultBean();
                resultOuter.setDomain("onlineRadio");
                resultOuter.setRequestType(requestType);
                response.setErrorCode("insufficientAccount");
                resultOuter.setRequestResult(response);
                try {
                    SDSResponse.getInstance(this).sendResponse(requestId, new Gson().toJson(resultOuter), false);
                } catch (RemoteException e) {
                    e.printStackTrace();
                }
                return;
            }


            Constants.LastModeFlag = false;
            if ("getPlayStatus".equals(requestType)) {
                setPlayStatus(requestId);
            } else if ("showSpecificView".equals(requestType)) {
                showSpecificView(requestId);
            } else if ("playControl".equals(requestType)) {
                playControl(jsonParam, requestId);
            } else if ("searchOnlineStation".equals(requestType)) {
                searchOnlineRadio(jsonParam, requestId);
            } else if ("playSpecifiedStation".equals(requestType)) {
                playSpecStation(jsonParam, requestId);
            } else if ("addIntoFavoriteList".equals(requestType)) {
                addFav(requestId);
            } else if ("removeFromFavoriteList".equals(requestType)) {
                removeFav(requestId);
            } else if ("playSpecificList".equals(requestType)) {
                playSpecificList(jsonParam, requestId);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }


    /**
     * 播放指定列表 默认从第一个开始
     *
     * @param jsonParam
     * @param requestId
     */
    private void playSpecificList(String jsonParam, String requestId) {
        List<Track> datas = new ArrayList<>();
        SDSPlayControlParambean param = new Gson().fromJson(jsonParam, SDSPlayControlParambean.class);
        String specList = param.getRequestParam().getListType();


        SDSCommonOuterResultBean outer = new SDSCommonOuterResultBean();
        outer.setDomain("onlineRadio");
        outer.setRequestType("playSpecificList");

//        String specList="historyList";


        if ("favoriteList".equals(specList)) {
            List<FavouriteAlbumDbBean> local_db = new ArrayList<>();
            try {
                local_db.addAll(helper.getFavouriteDao().queryBuilder().orderBy("timeStamp", false).where().eq("userId", MusicApplication.GetUserId()).and().eq("type", "album").query());
                if (local_db != null) {
                    Logger.i("local_db-->" + local_db.size());
                }
                if (local_db != null && local_db.size() > 0) {
                    if ("album".equals(local_db.get(0).getType())) {

                        /*Start by menglingqiang*/
                        Date dt = new Date();
                        try {
                            TracelogInterface inter = MusicApplication.getLogInterface();
                            if (inter != null) {
                                inter.sendLogData(dt.toString(), dt.toString(), PlayAlbumRadioService.this.getClass().getName(), "DEBUG", "400", "GetAlbumBrowse Request");
                            } else {
                                Log.e("JPCC", "inter == null");
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        /*End by menglingqiang*/

                        radioModel.GetAlbumBrowse(local_db.get(0).getId(), 1).subscribe(new CommonSubscriber<AlbumBrowseBean>() {
                            @Override
                            public void onSuccess(AlbumBrowseBean response) {
                                if ((response.getData().getTracks() != null) && (response.getData().getTracks().size() > 0)) {
                                    datas.addAll(response.getData().getTracks());
                                    for (Track track : datas) {
                                        track.setTrackIntro(response.getData().getAlbumIntro());
                                    }
                                    AlbumRadioAudioPlayer.get().setOnSources(datas, 0, 0, -1);
                                    SDSCommonResult responseSDS = new SDSCommonResult();
                                    responseSDS.setErrorCode("success");
                                    outer.setRequestResult(responseSDS);
                                    try {
                                        Logger.i("playSpecificList-->" + new Gson().toJson(outer));
                                        SDSResponse.getInstance(PlayAlbumRadioService.this).sendResponse(requestId, new Gson().toJson(outer), false);
                                    } catch (Exception e) {
                                        e.printStackTrace();
                                    }
                                }
                                /*Start by menglingqiang*/
                                Date dt = new Date();
                                try {
                                    TracelogInterface inter = MusicApplication.getLogInterface();
                                    if (inter != null) {
                                        inter.sendLogData(dt.toString(), dt.toString(), PlayAlbumRadioService.this.getClass().getName(), "DEBUG", "400", "GetAlbumBrowse onSuccess");
                                    } else {
                                        Log.e("JPCC", "inter == null");
                                    }
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                                /*End by menglingqiang*/
                            }

                            @Override
                            public void onFailure(BaseBean response) {


                                if (response.getCode() == Constants.ERROR_CODE_NOT_BIND || response.getCode() == Constants.ERROR_CODE_NOT_BIND2) {
                                    SDSCommonResult responseNotBind = new SDSCommonResult();
                                    SDSCommonOuterResultBean resultOuter = new SDSCommonOuterResultBean();
                                    resultOuter.setDomain("onlineRadio");
                                    resultOuter.setRequestType("playSpecificList");
                                    responseNotBind.setErrorCode("notBindCP");
                                    resultOuter.setRequestResult(responseNotBind);
                                    try {
                                        SDSResponse.getInstance(PlayAlbumRadioService.this).sendResponse(requestId, new Gson().toJson(resultOuter), false);
                                    } catch (RemoteException e) {
                                        e.printStackTrace();
                                    }
                                } else {
                                    SDSCommonResult responseSDS = new SDSCommonResult();
                                    responseSDS.setErrorCode("failed");
                                    outer.setRequestResult(responseSDS);
                                    try {
                                        Logger.i("playSpecificList-->" + new Gson().toJson(outer));
                                        SDSResponse.getInstance(PlayAlbumRadioService.this).sendResponse(requestId, new Gson().toJson(outer), false);
                                    } catch (Exception e) {
                                        e.printStackTrace();
                                    }
                                    /*Start by menglingqiang*/
                                    Date dt = new Date();
                                    try {
                                        TracelogInterface inter = MusicApplication.getLogInterface();
                                        if (inter != null) {
                                            inter.sendLogData(dt.toString(), dt.toString(), PlayAlbumRadioService.this.getClass().getName(), "ERROR", "400", "GetAlbumBrowse onSuccess");
                                        } else {
                                            Log.e("JPCC", "inter == null");
                                        }
                                    } catch (Exception e) {
                                        e.printStackTrace();
                                    }
                                    /*End by menglingqiang*/
                                }
                            }
                        });
                    } else {
                        SDSCommonResult responseSDS = new SDSCommonResult();
                        responseSDS.setErrorCode("unsupported");
                        outer.setRequestResult(responseSDS);
                        try {
                            Logger.i("playSpecificList-->" + new Gson().toJson(outer));
                            SDSResponse.getInstance(PlayAlbumRadioService.this).sendResponse(requestId, new Gson().toJson(outer), false);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }


                    }
                } else {
                    SDSCommonResult response = new SDSCommonResult();
                    response.setErrorCode("listIsEmpty");
                    outer.setRequestResult(response);
                    SDSResponse.getInstance(this).sendResponse(requestId, new Gson().toJson(outer), false);
                    Logger.i("playSpecificList-->" + new Gson().toJson(outer));
                }
            } catch (SQLException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else if ("downloadList".equals(specList)) {
            try {
                List<DownloadTrackDbBean> resultQuerys = helper.getDownloadDao().queryBuilder().groupBy("albumId").where().eq("userId", MusicApplication.GetUserId()).query();
                List<DownloadTrackDbBean> datas_download = new ArrayList<>();
                if (resultQuerys != null && resultQuerys.size() > 0) {
                    datas_download.addAll(helper.getDownloadDao().queryBuilder().where().eq("albumId", resultQuerys.get(0).getAlbumId()).and().eq("userId", MusicApplication.GetUserId()).query());
                    List<Track> infos = new ArrayList<>();
                    for (DownloadTrackDbBean db : datas_download) {
                        Track track = new Track();
                        SubordinatedAlbum subordinatedAlbum = new SubordinatedAlbum();
                        subordinatedAlbum.setId(db.getAlbumId());
                        subordinatedAlbum.setAlbumTitle(db.getAlbumName());
                        Announcer announcer = new Announcer();
                        announcer.setNickname(db.getAuthor());
                        track.setId(db.getTrackId());
                        track.setTrackTitle(db.getTrackName());
                        track.setCoverUrlLarge(db.getCover());
                        track.setPlayUrl32(db.getTrackUrl());
                        track.setCanDownload(false);
                        track.setDownloadUrl("");
                        track.type = "album";
                        track.setAnnouncer(announcer);
                        track.setSubordinatedAlbum(subordinatedAlbum);
                        infos.add(track);
                    }
                    AlbumRadioAudioPlayer.get().setOnSources(infos, 0, 1, -1);
                    SDSCommonResult responseSDS = new SDSCommonResult();
                    responseSDS.setErrorCode("success");
                    outer.setRequestResult(responseSDS);
                    try {
                        Logger.i("playSpecificList-->" + new Gson().toJson(outer));
                        SDSResponse.getInstance(PlayAlbumRadioService.this).sendResponse(requestId, new Gson().toJson(outer), false);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                } else {
                    SDSCommonResult response = new SDSCommonResult();
                    response.setErrorCode("listIsEmpty");
                    outer.setRequestResult(response);
                    Logger.i("playSpecificList-->" + new Gson().toJson(outer));
                    SDSResponse.getInstance(this).sendResponse(requestId, new Gson().toJson(outer), false);
                }
            } catch (SQLException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else if ("topList".equals(specList)) {


            String subListName = param.getRequestParam().getSubListName();


            if (TextUtils.isEmpty(subListName)) {
                radioModel.RadioRanks(1).flatMap(new Func1<TopListBean, Observable<AlbumBrowseBean>>() {
                    @Override
                    public Observable<AlbumBrowseBean> call(TopListBean topListBean) {
                        if (topListBean.getData() != null && topListBean.getData().getPageData() != null && topListBean.getData().getPageData().size() > 0) {
                            return radioModel.RadioRanksById((int) topListBean.getData().getPageData().get(0).getId(), 1).flatMap(new Func1<TopListAlbumBean, Observable<AlbumBrowseBean>>() {
                                @Override
                                public Observable<AlbumBrowseBean> call(TopListAlbumBean topListAlbumBean) {
                                    if (topListAlbumBean.getData() != null && topListAlbumBean.getData().getPageData() != null && topListAlbumBean.getData().getPageData().size() > 0) {
                                        return radioModel.GetAlbumBrowse(topListAlbumBean.getData().getPageData().get(0).getId(), 1);
                                    } else {
                                        if (topListAlbumBean.getCode() == Constants.ERROR_CODE_NOT_BIND || topListAlbumBean.getCode() == Constants.ERROR_CODE_NOT_BIND2) {
                                            AlbumBrowseBean response = new AlbumBrowseBean();
                                            response.setCode(-2019);
                                            return Observable.just(response);
                                        } else {
                                            AlbumBrowseBean response = new AlbumBrowseBean();
                                            response.setCode(-1);
                                            return Observable.just(response);
                                        }
                                    }
                                }
                            });
                        } else {

//                            if(response.getCode()==Constants.ERROR_CODE_NOT_BIND||response.getCode()==Constants.ERROR_CODE_NOT_BIND2){
//                                SDSCommonResult responseNotBind = new SDSCommonResult();
//                                SDSCommonOuterResultBean resultOuter = new SDSCommonOuterResultBean();
//                                resultOuter.setDomain("onlineRadio");
//                                resultOuter.setRequestType("playSpecificList");
//                                responseNotBind.setErrorCode("notBindCP");
//                                resultOuter.setRequestResult(responseNotBind);
//                                try {
//                                    SDSResponse.getInstance(PlayAlbumRadioService.this).sendResponse(requestId, new Gson().toJson(resultOuter), false);
//                                } catch (RemoteException e) {
//                                    e.printStackTrace();
//                                }
//                            }


                            if (topListBean.getCode() == Constants.ERROR_CODE_NOT_BIND || topListBean.getCode() == Constants.ERROR_CODE_NOT_BIND2) {
                                AlbumBrowseBean response = new AlbumBrowseBean();
                                response.setCode(-2019);
                                return Observable.just(response);
                            } else {
                                AlbumBrowseBean response = new AlbumBrowseBean();
                                response.setCode(-1);
                                return Observable.just(response);
                            }
                        }
                    }
                }).subscribe(new CommonSubscriber<AlbumBrowseBean>() {
                    @Override
                    public void onSuccess(AlbumBrowseBean response) {
                        if ((response.getData().getTracks() != null) && (response.getData().getTracks().size() > 0)) {
                            List<Track> tempTracks = new ArrayList<>();
                            tempTracks.addAll(response.getData().getTracks());
                            for (Track track : tempTracks) {
                                track.setTrackIntro(response.getData().getAlbumIntro());
                            }
                            AlbumRadioAudioPlayer.get().setOnSources(tempTracks, 0, 4, -1);

                            SDSCommonResult responseSDS = new SDSCommonResult();
                            responseSDS.setErrorCode("success");
                            outer.setRequestResult(responseSDS);
                            try {
                                Logger.i("topList-->" + new Gson().toJson(outer));
                                SDSResponse.getInstance(PlayAlbumRadioService.this).sendResponse(requestId, new Gson().toJson(outer), false);
                            } catch (Exception e) {
                                e.printStackTrace();
                            }

                        } else {
                            SDSCommonResult responseSDS = new SDSCommonResult();
                            responseSDS.setErrorCode("listIsEmpty");
                            outer.setRequestResult(responseSDS);
                            try {
                                Logger.i("topList-->" + new Gson().toJson(outer));
                                SDSResponse.getInstance(PlayAlbumRadioService.this).sendResponse(requestId, new Gson().toJson(outer), false);
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                        /*Start by menglingqiang*/
                        Date dt = new Date();
                        try {
                            TracelogInterface inter = MusicApplication.getLogInterface();
                            if (inter != null) {
                                inter.sendLogData(dt.toString(), dt.toString(), PlayAlbumRadioService.this.getClass().getName(), "DEBUG", "400", "GetAlbumBrowse onSuccess");
                            } else {
                                Log.e("JPCC", "inter == null");
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onFailure(BaseBean response) {


                        if (response.getCode() == -2019) {
                            SDSCommonResult responseSDS = new SDSCommonResult();
                            responseSDS.setErrorCode("notBindCP");
                            outer.setRequestResult(responseSDS);
                            try {
                                Logger.i("topList-->" + new Gson().toJson(outer));
                                SDSResponse.getInstance(PlayAlbumRadioService.this).sendResponse(requestId, new Gson().toJson(outer), false);
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        } else {
                            SDSCommonResult responseSDS = new SDSCommonResult();
                            responseSDS.setErrorCode("failed");
                            outer.setRequestResult(responseSDS);
                            try {
                                Logger.i("topList-->" + new Gson().toJson(outer));
                                SDSResponse.getInstance(PlayAlbumRadioService.this).sendResponse(requestId, new Gson().toJson(outer), false);
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    }
                });
            } else {
                radioModel.RadioRanks(1).flatMap(new Func1<TopListBean, Observable<AlbumBrowseBean>>() {
                    @Override
                    public Observable<AlbumBrowseBean> call(TopListBean topListBean) {
                        if (topListBean.getData() != null && topListBean.getData().getPageData() != null && topListBean.getData().getPageData().size() > 0) {
                            boolean flagExist = false;
                            long topAlbumId = 0;
//                            long albumId=-1;
                            for (TopListData topListData : topListBean.getData().getPageData()) {
                                if (subListName.equals(topListData.getTitle())) {
                                    flagExist = true;
                                    topAlbumId = topListData.getId();
                                    break;
                                }
                            }
                            if (flagExist) {
                                return radioModel.RadioRanksById((int) topAlbumId, 1).flatMap(new Func1<TopListAlbumBean, Observable<AlbumBrowseBean>>() {
                                    @Override
                                    public Observable<AlbumBrowseBean> call(TopListAlbumBean topListAlbumBean) {
                                        if (topListAlbumBean.getData() != null && topListAlbumBean.getData().getPageData() != null && topListAlbumBean.getData().getPageData().size() > 0) {
                                            return radioModel.GetAlbumBrowse(topListAlbumBean.getData().getPageData().get(0).getId(), 1);
                                        } else {

                                            if (topListAlbumBean.getCode() == Constants.ERROR_CODE_NOT_BIND || topListAlbumBean.getCode() == Constants.ERROR_CODE_NOT_BIND2) {
                                                AlbumBrowseBean response = new AlbumBrowseBean();
                                                response.setCode(-2019);
                                                return Observable.just(response);
                                            } else {
                                                AlbumBrowseBean response = new AlbumBrowseBean();
                                                response.setCode(-1);
                                                return Observable.just(response);
                                            }
                                        }
                                    }
                                });
                            } else {
                                AlbumBrowseBean response = new AlbumBrowseBean();
                                response.setCode(-1);
                                return Observable.just(response);
                            }
                        } else {


                            if (topListBean.getCode() == Constants.ERROR_CODE_NOT_BIND || topListBean.getCode() == Constants.ERROR_CODE_NOT_BIND2) {
                                AlbumBrowseBean response = new AlbumBrowseBean();
                                response.setCode(-2019);
                                return Observable.just(response);
                            } else {
                                AlbumBrowseBean response = new AlbumBrowseBean();
                                response.setCode(-1);
                                return Observable.just(response);
                            }
                        }


                    }
                }).subscribe(new CommonSubscriber<AlbumBrowseBean>() {
                    @Override
                    public void onSuccess(AlbumBrowseBean response) {
                        if ((response.getData().getTracks() != null) && (response.getData().getTracks().size() > 0)) {
                            List<Track> tempTracks = new ArrayList<>();
                            tempTracks.addAll(response.getData().getTracks());
                            for (Track track : tempTracks) {
                                track.setTrackIntro(response.getData().getAlbumIntro());
                            }
                            AlbumRadioAudioPlayer.get().setOnSources(tempTracks, 0, 4, -1);

                            SDSCommonResult responseSDS = new SDSCommonResult();
                            responseSDS.setErrorCode("success");
                            outer.setRequestResult(responseSDS);
                            try {
                                Logger.i("topList-->" + new Gson().toJson(outer));
                                SDSResponse.getInstance(PlayAlbumRadioService.this).sendResponse(requestId, new Gson().toJson(outer), false);
                            } catch (Exception e) {
                                e.printStackTrace();
                            }

                        } else {
                            SDSCommonResult responseSDS = new SDSCommonResult();
                            responseSDS.setErrorCode("listIsEmpty");
                            outer.setRequestResult(responseSDS);
                            try {
                                Logger.i("topList-->" + new Gson().toJson(outer));
                                SDSResponse.getInstance(PlayAlbumRadioService.this).sendResponse(requestId, new Gson().toJson(outer), false);
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                        /*Start by menglingqiang*/
                        Date dt = new Date();
                        try {
                            TracelogInterface inter = MusicApplication.getLogInterface();
                            if (inter != null) {
                                inter.sendLogData(dt.toString(), dt.toString(), PlayAlbumRadioService.this.getClass().getName(), "DEBUG", "400", "GetAlbumBrowse onSuccess");
                            } else {
                                Log.e("JPCC", "inter == null");
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onFailure(BaseBean response) {

                        if (-2019 == response.getCode()) {
                            SDSCommonResult responseSDS = new SDSCommonResult();
                            responseSDS.setErrorCode("notBindCP");
                            outer.setRequestResult(responseSDS);
                            try {
                                Logger.i("topList-->" + new Gson().toJson(outer));
                                SDSResponse.getInstance(PlayAlbumRadioService.this).sendResponse(requestId, new Gson().toJson(outer), false);
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        } else {
                            SDSCommonResult responseSDS = new SDSCommonResult();
                            responseSDS.setErrorCode("failed");
                            outer.setRequestResult(responseSDS);
                            try {
                                Logger.i("topList-->" + new Gson().toJson(outer));
                                SDSResponse.getInstance(PlayAlbumRadioService.this).sendResponse(requestId, new Gson().toJson(outer), false);
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    }
                });
            }


            /*Start by menglingqiang*/
//            Date dt = new Date();
//            try {
//                TracelogInterface inter = MusicApplication.getLogInterface();
//                if(inter != null){
//                    inter.sendLogData(dt.toString(),dt.toString(),PlayAlbumRadioService.this.getClass().getName(),"DEBUG","400","GetDailyRecommendations Request");
//                }else {
//                    Log.e("JPCC","inter == null");
//                }
//            } catch (Exception e) {
//                e.printStackTrace();
//            }
//            /*End by menglingqiang*/
//
//            radioModel.GetDailyRecommendations().flatMap(new Func1<DailyRecommendationBean, Observable<AlbumBrowseBean>>() {
//                @Override
//                public Observable<AlbumBrowseBean> call(DailyRecommendationBean dailyRecommendationBean) {
//                    return radioModel.GetAlbumBrowse(dailyRecommendationBean.getData().get(0).getAlbums().get(0).getId(), 1);
//                }
//            }).subscribe(new CommonSubscriber<AlbumBrowseBean>() {
//                @Override
//                public void onSuccess(AlbumBrowseBean response) {
//                    if ((response.getData().getTracks() != null) && (response.getData().getTracks().size() > 0)) {
//                        List<Track> tempTracks = new ArrayList<>();
//                        tempTracks.addAll(response.getData().getTracks());
//                        for (Track track : tempTracks) {
//                            track.setTrackIntro(response.getData().getAlbumIntro());
//                        }
//                        AlbumRadioAudioPlayer.get().setOnSources(tempTracks, 0, 4, -1);
//
//                        SDSCommonResult responseSDS = new SDSCommonResult();
//                        responseSDS.setErrorCode("success");
//                        outer.setRequestResult(responseSDS);
//                        try {
//                            Logger.i("topList-->" + new Gson().toJson(outer));
//                            SDSResponse.getInstance(PlayAlbumRadioService.this).sendResponse(requestId, new Gson().toJson(outer), false);
//                        } catch (Exception e) {
//                            e.printStackTrace();
//                        }
//
//                    } else {
//                        SDSCommonResult responseSDS = new SDSCommonResult();
//                        responseSDS.setErrorCode("listIsEmpty");
//                        outer.setRequestResult(responseSDS);
//                        try {
//                            Logger.i("topList-->" + new Gson().toJson(outer));
//                            SDSResponse.getInstance(PlayAlbumRadioService.this).sendResponse(requestId, new Gson().toJson(outer), false);
//                        } catch (Exception e) {
//                            e.printStackTrace();
//                        }
//                    }
//                    /*Start by menglingqiang*/
//                    Date dt = new Date();
//                    try {
//                        TracelogInterface inter = MusicApplication.getLogInterface();
//                        if(inter != null){
//                            inter.sendLogData(dt.toString(),dt.toString(),PlayAlbumRadioService.this.getClass().getName(),"DEBUG","400","GetAlbumBrowse onSuccess");
//                        }else {
//                            Log.e("JPCC","inter == null");
//                        }
//                    } catch (Exception e) {
//                        e.printStackTrace();
//                    }
//                    /*End by menglingqiang*/
//                }
//
//                @Override
//                public void onFailure(BaseBean response) {
//                    ToastUtils.show(response.getStatusMessage());
//                    SDSCommonResult responseSDS = new SDSCommonResult();
//                    responseSDS.setErrorCode("failed");
//                    outer.setRequestResult(responseSDS);
//                    try {
//                        Logger.i("topList-->" + new Gson().toJson(outer));
//                        SDSResponse.getInstance(PlayAlbumRadioService.this).sendResponse(requestId, new Gson().toJson(outer), false);
//                    } catch (Exception e) {
//                        e.printStackTrace();
//                    }
//                    /*Start by menglingqiang*/
//                    Date dt = new Date();
//                    try {
//                        TracelogInterface inter = MusicApplication.getLogInterface();
//                        if(inter != null){
//                            inter.sendLogData(dt.toString(),dt.toString(),PlayAlbumRadioService.this.getClass().getName(),"ERROR","400","GetAlbumBrowse onFailure");
//                        }else {
//                            Log.e("JPCC","inter == null");
//                        }
//                    } catch (Exception e) {
//                        e.printStackTrace();
//                    }
//                    /*End by menglingqiang*/
//                }
//            });


//            SDSCommonResult responseSDS = new SDSCommonResult();
//            responseSDS.setErrorCode("unsupported");
//            outer.setRequestResult(responseSDS);
//            try {
//                Logger.i("playSpecificList-->" + new Gson().toJson(outer));
//                SDSResponse.getInstance(PlayAlbumRadioService.this).sendResponse(requestId, new Gson().toJson(outer), false);
//            } catch (Exception e) {
//                e.printStackTrace();
//            }
        } else if ("historyList".equals(specList)) {
//            SDSPlayStatusBean responseSDS = new SDSPlayStatusBean();
//            responseSDS.setErrorCode("unsupported");
//            try {
//                SDSResponse.getInstance(PlayAlbumRadioService.this).sendResponse(requestId, new Gson().toJson(responseSDS), false);
//            } catch (Exception e) {
//                e.printStackTrace();
//            }


            helper = DatabaseHelperOrm.getHelper(this);
            List<RecentAlbumRadioTrackBean> local_results = null;
            List<RecentAlbumRadioTrackBean> results = new ArrayList<>();
            List<Track> infos = new ArrayList<>();
            try {
                local_results = helper.getRecentDao().queryBuilder().orderBy("timeStamp", false).where().eq("userId", MusicApplication.GetUserId()).query();
                if (local_results != null && local_results.size() > 0) {
                    results.addAll(local_results);
                    for (RecentAlbumRadioTrackBean source : results) {
                        Track track = new Track();
                        SubordinatedAlbum subordinatedAlbum = new SubordinatedAlbum();
                        subordinatedAlbum.setId(source.getAlbumId());
                        subordinatedAlbum.setAlbumTitle(source.getAlbumName());
                        Announcer announcer = new Announcer();
                        announcer.setNickname(source.getAuthor());
                        track.setId(source.getTrackId());
                        track.setTrackTitle(source.getTrackName());
                        track.setCoverUrlLarge(source.getCover());
                        if ("album".equals(source.getType())) {
                            track.setPlayUrl32(source.getTrackUrl());
                            track.setCanDownload(true);
                            track.setDownloadUrl(source.getDownloadUrl());
                            track.type = "album";
                        } else {
                            track.setPlayUrl32(source.getRadioLivingUrl());
                            track.setCanDownload(false);
                            track.setDownloadUrl("");
                            track.type = "radio";
                        }
                        track.setAnnouncer(announcer);
                        track.setSubordinatedAlbum(subordinatedAlbum);
                        infos.add(track);
                    }
                    AlbumRadioAudioPlayer.get().setOnSources(infos, 0, 4, -1);

                    SDSCommonResult responseSDS = new SDSCommonResult();
                    responseSDS.setErrorCode("success");
                    outer.setRequestResult(responseSDS);
                    try {
                        Logger.i("playSpecificList-->" + new Gson().toJson(outer));
                        SDSResponse.getInstance(PlayAlbumRadioService.this).sendResponse(requestId, new Gson().toJson(outer), false);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                } else {
                    SDSCommonResult responseSDS = new SDSCommonResult();
                    responseSDS.setErrorCode("listIsEmpty");
                    outer.setRequestResult(responseSDS);
                    try {
                        Logger.i("playSpecificList-->" + new Gson().toJson(outer));
                        SDSResponse.getInstance(PlayAlbumRadioService.this).sendResponse(requestId, new Gson().toJson(outer), false);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            } catch (SQLException e) {
                e.printStackTrace();
                SDSCommonResult responseSDS = new SDSCommonResult();
                responseSDS.setErrorCode("failed");
                outer.setRequestResult(responseSDS);
                try {
                    Logger.i("playSpecificList-->" + new Gson().toJson(outer));
                    SDSResponse.getInstance(PlayAlbumRadioService.this).sendResponse(requestId, new Gson().toJson(outer), false);
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
        }
    }


    private void removeFav(String requestId) {


        SDSCommonOuterResultBean resultOuter = new SDSCommonOuterResultBean();
        resultOuter.setDomain("onlineRadio");
        resultOuter.setRequestType("removeFromFavoriteList");


        if (AlbumRadioAudioPlayer.get().getPlayMusic() != null) {
            try {
                FavouriteAlbumDbBean data = DatabaseHelperOrm.getHelper(this).getFavouriteDao().queryBuilder().where().eq("userId", MusicApplication.GetUserId()).and().eq("id", AlbumRadioAudioPlayer.get().getPlayMusic().getAlbumId()).queryForFirst();
                DatabaseHelperOrm.getHelper(this).getFavouriteDao().delete(data);
                SDSCommonResult response = new SDSCommonResult();
                response.setErrorCode("success");
                resultOuter.setRequestResult(response);
                SDSResponse.getInstance(this).sendResponse(requestId, new Gson().toJson(resultOuter), false);
                ToastUtils.show(R.string.string_58);
            } catch (SQLException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            SDSCommonResult response = new SDSCommonResult();
            response.setErrorCode("failed");
            resultOuter.setRequestResult(response);
            try {
                SDSResponse.getInstance(this).sendResponse(requestId, new Gson().toJson(resultOuter), false);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }


    private void addFav(String requestId) {


        SDSCommonOuterResultBean resultOuter = new SDSCommonOuterResultBean();
        resultOuter.setDomain("onlineRadio");
        resultOuter.setRequestType("addIntoFavoriteList");
        if (AlbumRadioAudioPlayer.get().getPlayMusic() != null) {
            FavouriteAlbumDbBean result = new FavouriteAlbumDbBean();
            result.setUserId(MusicApplication.GetUserId());
            result.setId(AlbumRadioAudioPlayer.get().getPlayMusic().getAlbumId());
            result.setName(AlbumRadioAudioPlayer.get().getPlayMusic().getAlbumName());
            result.setHostName(AlbumRadioAudioPlayer.get().getPlayMusic().getAuthor());
            result.setCoverUrlLarge(AlbumRadioAudioPlayer.get().getPlayMusic().getCover());
            result.setType(AlbumRadioAudioPlayer.get().getPlayMusic().getType());
            result.setTimeStamp(new Date().getTime());
            try {

                if ("album".equals(AlbumRadioAudioPlayer.get().getPlayMusic().getType())) {
                    result.setType("album");
                    Logger.i("addFav-->" + "size1=" + helper.getFavouriteDao().queryBuilder().orderBy("timeStamp", false).where().eq("userId", MusicApplication.GetUserId()).query().size());
                    FavouriteAlbumDbBean data = DatabaseHelperOrm.getHelper(PlayAlbumRadioService.this).getFavouriteDao().queryBuilder().where().eq("userId", MusicApplication.GetUserId()).and().eq("id", AlbumRadioAudioPlayer.get().getPlayMusic().getAlbumId()).queryForFirst();
                    if (data == null) {
                        ToastUtils.show(R.string.string_57);
                        DatabaseHelperOrm.getHelper(this).getFavouriteDao().create(result);
                        SDSCommonResult response = new SDSCommonResult();
                        response.setErrorCode("success");
                        resultOuter.setRequestResult(response);
                        SDSResponse.getInstance(this).sendResponse(requestId, new Gson().toJson(resultOuter), false);
                        Logger.i("addFav-->" + "success");
                        Logger.i("addFav-->" + new Gson().toJson(result));
                        Logger.i("addFav-->" + "size2=" + helper.getFavouriteDao().queryBuilder().orderBy("timeStamp", false).where().eq("userId", MusicApplication.GetUserId()).query().size());
                    }
                } else if ("radio".equals(AlbumRadioAudioPlayer.get().getPlayMusic().getType())) {
                    result.setType("radio");
                    Logger.i("addFav-->" + "size1=" + helper.getFavouriteDao().queryBuilder().orderBy("timeStamp", false).where().eq("userId", MusicApplication.GetUserId()).query().size());
                    FavouriteAlbumDbBean data = DatabaseHelperOrm.getHelper(PlayAlbumRadioService.this).getFavouriteDao().queryBuilder().where().eq("userId", MusicApplication.GetUserId()).and().eq("id", AlbumRadioAudioPlayer.get().getPlayMusic().getAlbumId()).queryForFirst();
                    if (data == null) {
                        ToastUtils.show(R.string.string_57);
                        DatabaseHelperOrm.getHelper(this).getFavouriteDao().create(result);
                        SDSCommonResult response = new SDSCommonResult();
                        response.setErrorCode("success");
                        resultOuter.setRequestResult(response);
                        SDSResponse.getInstance(this).sendResponse(requestId, new Gson().toJson(resultOuter), false);
                        Logger.i("addFav-->" + "success");
                        Logger.i("addFav-->" + new Gson().toJson(result));
                        Logger.i("addFav-->" + "size2=" + helper.getFavouriteDao().queryBuilder().orderBy("timeStamp", false).where().eq("userId", MusicApplication.GetUserId()).query().size());
                    }
                } else {
                    SDSCommonResult response = new SDSCommonResult();
                    response.setErrorCode("unsupported");
                    resultOuter.setRequestResult(response);
                    SDSResponse.getInstance(this).sendResponse(requestId, new Gson().toJson(resultOuter), false);
                }


            } catch (SQLException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            SDSCommonResult response = new SDSCommonResult();
            response.setErrorCode("failed");
            resultOuter.setRequestResult(response);
            try {
                SDSResponse.getInstance(this).sendResponse(requestId, new Gson().toJson(resultOuter), false);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        RefreshFavStatusAction action = new RefreshFavStatusAction();
        EventBus.getDefault().post(action);
    }


    /**
     * 播放指定电台
     *
     * @param jsonParam
     * @param requestId
     */
    private void playSpecStation(String jsonParam, String requestId) {
        SDSPlayControlParambean param = new Gson().fromJson(jsonParam, SDSPlayControlParambean.class);
        SDSStationInfo specStation = param.getRequestParam().getStationInfo();
        if (!specStation.isRadio()) {
            SDSCommonOuterResultBean resultOuter = new SDSCommonOuterResultBean();
            resultOuter.setDomain("onlineRadio");
            resultOuter.setRequestType("playSpecifiedStation");

            /*Start by menglingqiang*/
            Date dt = new Date();
            try {
                TracelogInterface inter = MusicApplication.getLogInterface();
                if (inter != null) {
                    inter.sendLogData(dt.toString(), dt.toString(), PlayAlbumRadioService.this.getClass().getName(), "DEBUG", "400", "GetAlbumBrowse Request");
                } else {
                    Log.e("JPCC", "inter == null");
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            /*End by menglingqiang*/

            radioModel.GetAlbumBrowse(specStation.getId(), 1).subscribe(new CommonSubscriber<AlbumBrowseBean>() {
                @Override
                public void onSuccess(AlbumBrowseBean response) {
                    if (response.getData() != null && response.getData().getTracks() != null && response.getData().getTracks().size() > 0) {
                        AlbumRadioAudioPlayer.get().setOnSources(response.getData().getTracks(), 0, 4, -1);
                        SDSCommonResult responseToLinux = new SDSCommonResult();
                        responseToLinux.setErrorCode("success");
                        resultOuter.setRequestResult(responseToLinux);
                        try {
                            SDSResponse.getInstance(PlayAlbumRadioService.this).sendResponse(requestId, new Gson().toJson(resultOuter), false);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    } else {
                        SDSCommonResult responseToLinux = new SDSCommonResult();
                        responseToLinux.setErrorCode("listIsEmpty");
                        resultOuter.setRequestResult(responseToLinux);
                        try {
                            SDSResponse.getInstance(PlayAlbumRadioService.this).sendResponse(requestId, new Gson().toJson(resultOuter), false);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                    /*Start by menglingqiang*/
                    Date dt = new Date();
                    try {
                        TracelogInterface inter = MusicApplication.getLogInterface();
                        if (inter != null) {
                            inter.sendLogData(dt.toString(), dt.toString(), PlayAlbumRadioService.this.getClass().getName(), "DEBUG", "400", "GetAlbumBrowse onSuccess");
                        } else {
                            Log.e("JPCC", "inter == null");
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    /*End by menglingqiang*/
                }

                @Override
                public void onFailure(BaseBean response) {


                    if (response.getCode() == Constants.ERROR_CODE_NOT_BIND || response.getCode() == Constants.ERROR_CODE_NOT_BIND2) {
                        SDSCommonResult responseNotBind = new SDSCommonResult();
                        SDSCommonOuterResultBean resultOuter = new SDSCommonOuterResultBean();
                        resultOuter.setDomain("onlineRadio");
                        resultOuter.setRequestType("playSpecifiedStation");
                        responseNotBind.setErrorCode("notBindCP");
                        resultOuter.setRequestResult(responseNotBind);
                        try {
                            SDSResponse.getInstance(PlayAlbumRadioService.this).sendResponse(requestId, new Gson().toJson(resultOuter), false);
                        } catch (RemoteException e) {
                            e.printStackTrace();
                        }
                    } else {
                        SDSCommonResult responseToLinux = new SDSCommonResult();
                        responseToLinux.setErrorCode("failed");
                        resultOuter.setRequestResult(responseToLinux);
                        try {
                            SDSResponse.getInstance(PlayAlbumRadioService.this).sendResponse(requestId, new Gson().toJson(resultOuter), false);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        /*Start by menglingqiang*/
                        Date dt = new Date();
                        try {
                            TracelogInterface inter = MusicApplication.getLogInterface();
                            if (inter != null) {
                                inter.sendLogData(dt.toString(), dt.toString(), PlayAlbumRadioService.this.getClass().getName(), "ERROR", "400", "GetAlbumBrowse onSuccess");
                            } else {
                                Log.e("JPCC", "inter == null");
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        /*End by menglingqiang*/
                    }
                }
            });
        } else {
            SDSCommonOuterResultBean resultOuter = new SDSCommonOuterResultBean();
            resultOuter.setDomain("onlineRadio");
            resultOuter.setRequestType("playSpecifiedStation");

            /*Start by menglingqiang*/
            Date dt = new Date();
            try {
                TracelogInterface inter = MusicApplication.getLogInterface();
                if (inter != null) {
                    inter.sendLogData(dt.toString(), dt.toString(), PlayAlbumRadioService.this.getClass().getName(), "DEBUG", "400", "GetPlayingProgramDetail Request");
                } else {
                    Log.e("JPCC", "inter == null");
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            /*End by menglingqiang*/

            radioModel.GetPlayingProgramDetail(specStation.getId()).subscribe(new CommonSubscriber<LiveRadioDetailBean>() {
                @Override
                public void onSuccess(LiveRadioDetailBean response) {
                    if (response.getData() != null) {
                        Track track = new Track();
                        SubordinatedAlbum subordinatedAlbum = new SubordinatedAlbum();
                        subordinatedAlbum.setId(specStation.getId());
                        subordinatedAlbum.setAlbumTitle(specStation.getName());
                        Announcer announcer = new Announcer();
                        announcer.setNickname("");
                        track.setId(response.getData().getId());
                        track.setTrackTitle(response.getData().getProgramName());
                        track.setCoverUrlLarge(response.getData().getBackPicUrl());
                        track.setPlayUrl32(response.getData().getRate24AacUrl());
                        track.setCanDownload(false);
                        track.setDownloadUrl("");
                        track.type = "radio";
                        track.setSubordinatedAlbum(subordinatedAlbum);
                        track.setAnnouncer(announcer);
                        List<Track> sources = new ArrayList<>();
                        sources.add(track);
                        AlbumRadioAudioPlayer.get().setOnSources(sources, 0, 4, -1);
                        SDSCommonResult responseToLinux = new SDSCommonResult();
                        responseToLinux.setErrorCode("success");
                        resultOuter.setRequestResult(responseToLinux);
                        try {
                            SDSResponse.getInstance(PlayAlbumRadioService.this).sendResponse(requestId, new Gson().toJson(resultOuter), false);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    } else {
                        SDSCommonResult responseToLinux = new SDSCommonResult();
                        responseToLinux.setErrorCode("failed");
                        resultOuter.setRequestResult(responseToLinux);
                        try {
                            SDSResponse.getInstance(PlayAlbumRadioService.this).sendResponse(requestId, new Gson().toJson(resultOuter), false);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                    /*Start by menglingqiang*/
                    Date dt = new Date();
                    try {
                        TracelogInterface inter = MusicApplication.getLogInterface();
                        if (inter != null) {
                            inter.sendLogData(dt.toString(), dt.toString(), PlayAlbumRadioService.this.getClass().getName(), "DEBUG", "400", "GetPlayingProgramDetail onSuccess");
                        } else {
                            Log.e("JPCC", "inter == null");
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    /*End by menglingqiang*/
                }

                @Override
                public void onFailure(BaseBean response) {


                    if (response.getCode() == Constants.ERROR_CODE_NOT_BIND || response.getCode() == Constants.ERROR_CODE_NOT_BIND2) {
                        SDSCommonResult responseNotBind = new SDSCommonResult();
                        SDSCommonOuterResultBean resultOuter = new SDSCommonOuterResultBean();
                        resultOuter.setDomain("onlineRadio");
                        resultOuter.setRequestType("searchOnlineStation");
                        responseNotBind.setErrorCode("notBindCP");
                        resultOuter.setRequestResult(responseNotBind);
                        try {
                            SDSResponse.getInstance(PlayAlbumRadioService.this).sendResponse(requestId, new Gson().toJson(resultOuter), false);
                        } catch (RemoteException e) {
                            e.printStackTrace();
                        }
                    } else {
                        SDSCommonResult responseToLinux = new SDSCommonResult();
                        responseToLinux.setErrorCode("failed");
                        resultOuter.setRequestResult(responseToLinux);
                        try {
                            SDSResponse.getInstance(PlayAlbumRadioService.this).sendResponse(requestId, new Gson().toJson(resultOuter), false);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        /*Start by menglingqiang*/
                        Date dt = new Date();
                        try {
                            TracelogInterface inter = MusicApplication.getLogInterface();
                            if (inter != null) {
                                inter.sendLogData(dt.toString(), dt.toString(), PlayAlbumRadioService.this.getClass().getName(), "ERROR", "400", "GetPlayingProgramDetail onFailure");
                            } else {
                                Log.e("JPCC", "inter == null");
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        /*End by menglingqiang*/
                    }
                }
            });
        }

    }


    /**
     * 搜索  暂时没有办法做 搜索接口暂时不完整
     *
     * @param jsonParam
     * @param requestId
     */
    private void searchOnlineRadio(String jsonParam, String requestId) {


        SDSearchOnlineStationOuterResultBean resultOuter = new SDSearchOnlineStationOuterResultBean();
//        resultOuter.setDomain("onlineRadio");
//        resultOuter.setRequestType("searchOnlineStation");
//        SDSearchOnlineStationResult result = new SDSearchOnlineStationResult();
//        result.setErrorCode("unsupported");
//        result.setStationList(new ArrayList<>());
//        resultOuter.setRequestResult(result);
//        try {
//            SDSResponse.getInstance(this).sendResponse(requestId, new Gson().toJson(resultOuter), false);
//        } catch (Exception e) {
//            e.printStackTrace();
//        }


        SDSPlayControlParambean param = new Gson().fromJson(jsonParam, SDSPlayControlParambean.class);
        String keyword = param.getRequestParam().getKeyword();
        if (!TextUtils.isEmpty(keyword.trim())) {
            radioModel.SearchAll(keyword, 10, 1).subscribe(new CommonSubscriber<CommonAlbumRadioSearchResultBean>() {
                @Override
                public void onSuccess(CommonAlbumRadioSearchResultBean response) {
                    if ((response.getAlbums() != null) && (response.getAlbums().size() == 0)) {
                        SDSearchOnlineStationResult result = new SDSearchOnlineStationResult();
                        result.setErrorCode("listIsEmpty");
                        result.setStationList(new ArrayList<>());
                        resultOuter.setRequestResult(result);
                        try {
                            SDSResponse.getInstance(PlayAlbumRadioService.this).sendResponse(requestId, new Gson().toJson(resultOuter), false);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    } else {
                        List<SDSStationInfo> stationList = new ArrayList<>();
                        for (SimpleAlbumRadioEntity searchResult : response.getAlbums()) {
                            SDSStationInfo info = new SDSStationInfo();
                            info.setId(searchResult.getAlbumId());
                            info.setName(searchResult.getTitle());
                            info.setHostName("");
                            info.setCoverUrlSmall(searchResult.getCover());
                            info.setCoverUrlMiddle(searchResult.getCover());
                            info.setCoverUrlLarge(searchResult.getCover());
                            if ("album".equals(searchResult.getType())) {
                                info.setRadio(false);
                            } else {
                                info.setRadio(true);
                            }
                            info.setProgramId(-1);
                            info.setProgramUrl("");
                            info.setProgramName("");
                            info.setFavorite(false);
                            stationList.add(info);
                        }
                        SDSearchOnlineStationResult result = new SDSearchOnlineStationResult();
                        result.setErrorCode("success");
                        result.setStationList(stationList);
                        resultOuter.setRequestResult(result);
                        try {
                            SDSResponse.getInstance(PlayAlbumRadioService.this).sendResponse(requestId, new Gson().toJson(resultOuter), false);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }

                @Override
                public void onFailure(BaseBean response) {

                    if (response.getCode() == Constants.ERROR_CODE_NOT_BIND || response.getCode() == Constants.ERROR_CODE_NOT_BIND2) {
                        SDSCommonResult responseNotBind = new SDSCommonResult();
                        SDSCommonOuterResultBean resultOuter = new SDSCommonOuterResultBean();
                        resultOuter.setDomain("onlineRadio");
                        resultOuter.setRequestType("searchOnlineStation");
                        responseNotBind.setErrorCode("notBindCP");
                        resultOuter.setRequestResult(responseNotBind);
                        try {
                            SDSResponse.getInstance(PlayAlbumRadioService.this).sendResponse(requestId, new Gson().toJson(resultOuter), false);
                        } catch (RemoteException e) {
                            e.printStackTrace();
                        }
                    } else {
                        SDSearchOnlineStationResult result = new SDSearchOnlineStationResult();
                        result.setErrorCode("failed");
                        result.setStationList(new ArrayList<>());
                        resultOuter.setRequestResult(result);
                        try {
                            SDSResponse.getInstance(PlayAlbumRadioService.this).sendResponse(requestId, new Gson().toJson(resultOuter), false);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }
            });
        } else {
//            SDSearchOnlineStationResult result = new SDSearchOnlineStationResult();
//            result.setErrorCode("failed");
//            result.setStationList(new ArrayList<>());
//            resultOuter.setRequestResult(result);
//            try {
//                SDSResponse.getInstance(this).sendResponse(requestId, new Gson().toJson(resultOuter), false);
//            } catch (Exception e) {
//                e.printStackTrace();
//            }


            if (AlbumRadioAudioPlayer.get().getPlayMusic() != null) {
                List<SDSStationInfo> stationList = new ArrayList<>();
                SDSStationInfo info = new SDSStationInfo();
                info.setId(AlbumRadioAudioPlayer.get().getPlayMusic().getAlbumId());
                info.setName(AlbumRadioAudioPlayer.get().getPlayMusic().getAlbumName());
                info.setHostName(AlbumRadioAudioPlayer.get().getPlayMusic().getAuthor());
                info.setCoverUrlSmall(AlbumRadioAudioPlayer.get().getPlayMusic().getCover());
                info.setCoverUrlMiddle(AlbumRadioAudioPlayer.get().getPlayMusic().getCover());
                info.setCoverUrlLarge(AlbumRadioAudioPlayer.get().getPlayMusic().getCover());
                info.setRadio(false);
                info.setProgramId(-1);
                info.setProgramUrl("");
                info.setProgramName("");
                info.setFavorite(false);
                stationList.add(info);
                SDSearchOnlineStationResult result = new SDSearchOnlineStationResult();
                result.setErrorCode("success");
                result.setStationList(stationList);
                resultOuter.setRequestResult(result);
                try {
                    SDSResponse.getInstance(PlayAlbumRadioService.this).sendResponse(requestId, new Gson().toJson(resultOuter), false);
                    Logger.i("AlbumRadioAudioPlayer Status-->" + AlbumRadioAudioPlayer.get().isPausing());
                    if (AlbumRadioAudioPlayer.get().isPausing()) {
                        AlbumRadioAudioPlayer.get().playPause();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else {
//                SDSearchOnlineStationResult result = new SDSearchOnlineStationResult();
//                result.setErrorCode("invalidParam");
//                result.setStationList(new ArrayList<>());
//                resultOuter.setRequestResult(result);
//                try {
//                    SDSResponse.getInstance(this).sendResponse(requestId, new Gson().toJson(resultOuter), false);
//                    Logger.i("searchOnlineRadio-->" + new Gson().toJson(resultOuter));
//                } catch (Exception e) {
//                    e.printStackTrace();
//                }


                if (radioModel == null) {
                    radioModel = new RadioImpl();
                }
                radioModel.RadioRanks(1).flatMap(new Func1<TopListBean, Observable<AlbumBrowseBean>>() {
                    @Override
                    public Observable<AlbumBrowseBean> call(TopListBean topListBean) {
                        if (topListBean.getCode() == 0 && topListBean.getData() != null && topListBean.getData().getPageData() != null && topListBean.getData().getPageData().size() > 0) {
                            return radioModel.RadioRanksById((int) (topListBean.getData().getPageData().get(0).getId()), 1).flatMap(new Func1<TopListAlbumBean, Observable<AlbumBrowseBean>>() {
                                @Override
                                public Observable<AlbumBrowseBean> call(TopListAlbumBean topListAlbumBean) {
                                    if (topListAlbumBean.getData() != null && topListAlbumBean.getData().getPageData() != null && topListAlbumBean.getData().getPageData().size() > 0) {
                                        return radioModel.GetAlbumBrowse(topListAlbumBean.getData().getPageData().get(0).getId(), 1);
                                    } else {
                                        AlbumBrowseBean response = new AlbumBrowseBean();
                                        response.setCode(-1);
                                        response.setStatusMessage("Net Work Error");
                                        return Observable.just(response);
                                    }
                                }
                            });
                        } else {
                            AlbumBrowseBean response = new AlbumBrowseBean();
                            response.setCode(-1);
                            response.setStatusMessage("Net Work Error");
                            return Observable.just(response);
                        }
                    }
                }).compose(TransformUtils.defaultSchedulers()).subscribe(new CommonSubscriber<AlbumBrowseBean>() {
                    @Override
                    public void onSuccess(AlbumBrowseBean response) {
                        List<SDSStationInfo> stationList = new ArrayList<>();
                        for (Track data : response.getData().getTracks()) {
                            SDSStationInfo info = new SDSStationInfo();
                            info.setId(data.getId());
                            info.setName(data.getTrackTitle());
                            info.setHostName("");
                            info.setCoverUrlSmall(data.getCoverUrlLarge());
                            info.setCoverUrlMiddle(data.getCoverUrlLarge());
                            info.setCoverUrlLarge(data.getCoverUrlLarge());
                            info.setRadio(false);
                            info.setProgramId(-1);
                            info.setProgramUrl("");
                            info.setProgramName("");
                            info.setFavorite(false);
//                            info.setDuration(1000);
                            stationList.add(info);
                        }
                        SDSearchOnlineStationResult result = new SDSearchOnlineStationResult();
                        result.setErrorCode("success");
                        result.setStationList(stationList);
                        resultOuter.setRequestResult(result);
                        try {
                            SDSResponse.getInstance(PlayAlbumRadioService.this).sendResponse(requestId, new Gson().toJson(resultOuter), false);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        AlbumRadioAudioPlayer.get().setOnSources(response.getData().getTracks(), 0, 4, 0);
                    }

                    @Override
                    public void onFailure(BaseBean response) {
                        SDSearchOnlineStationResult result = new SDSearchOnlineStationResult();
                        result.setErrorCode("invalidParam");
                        result.setStationList(new ArrayList<>());
                        resultOuter.setRequestResult(result);
                        try {
                            SDSResponse.getInstance(PlayAlbumRadioService.this).sendResponse(requestId, new Gson().toJson(resultOuter), false);
                            Logger.i("searchOnlineRadio-->" + new Gson().toJson(resultOuter));
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                });
            }
        }
    }


    /**
     * 播放控制
     *
     * @param jsonParam
     */
    private void playControl(String jsonParam, String requestId) {
        SDSPlayControlParambean param = new Gson().fromJson(jsonParam, SDSPlayControlParambean.class);
        String playControl = param.getRequestParam().getControlType();
        SDSCommonResult response = new SDSCommonResult();


        SDSCommonOuterResultBean resultOuter = new SDSCommonOuterResultBean();
        resultOuter.setDomain("onlineRadio");
        resultOuter.setRequestType("playControl");


        if (AlbumRadioAudioPlayer.get().getPlayMusic() != null) {
            if ("play".equals(playControl)) {
                if (AlbumRadioAudioPlayer.get().isPausing()) {
                    AlbumRadioAudioPlayer.get().playPause();
                }
            }
            if ("pause".equals(playControl)) {
                AlbumRadioAudioPlayer.get().pausePlayer();
                Constants.FLAG_PAUSE_MANUAL = false;
            }
            if ("next".equals(playControl)) {
                Constants.FLAG_PAUSE_MANUAL = false;
                AlbumRadioAudioPlayer.get().next();
            }
            if ("previous".equals(playControl)) {
                Constants.FLAG_PAUSE_MANUAL = false;
                AlbumRadioAudioPlayer.get().prev();
            }
            response.setErrorCode("success");
            resultOuter.setRequestResult(response);
        } else {
            response.setErrorCode("failed");
            resultOuter.setRequestResult(response);
        }
        try {
            SDSResponse.getInstance(this).sendResponse(requestId, new Gson().toJson(resultOuter), false);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    private void showSpecificView(String requestId) {
        SDSCommonResult responseSDS = new SDSCommonResult();
        responseSDS.setErrorCode("success");

        SDSCommonOuterResultBean resultOuter = new SDSCommonOuterResultBean();
        resultOuter.setDomain("onlineRadio");
        resultOuter.setRequestType("showSpecificView");

        resultOuter.setRequestResult(responseSDS);

        try {
            SDSResponse.getInstance(PlayAlbumRadioService.this).sendResponse(requestId, new Gson().toJson(resultOuter), false);
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            Intent intent = this.getPackageManager().getLaunchIntentForPackage("com.jpcc.vw.personalcenter");
            intent.putExtra("mediaType", 1);
            intent.putExtra("jumpType", 2);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(intent);
        } catch (Exception e) {
            Toast.makeText(this, "Personal Center not installed", Toast.LENGTH_SHORT).show();
        }
    }

    private void setPlayStatus(String requestId) {
        SDSStationInfo stationInfo = new SDSStationInfo();
        SDSPlayStatusBean result = new SDSPlayStatusBean();
        SDSOuterResultBean resultOuter = new SDSOuterResultBean();
        resultOuter.setDomain("onlineRadio");
        resultOuter.setRequestType("getPlayStatus");
        if (PreferenceUtils.GetAudioFocusStatus()) {
            result.setSourceOn(true);
        } else {
            result.setSourceOn(false);
        }
        try {
//            RecentAlbumRadioTrackBean recent = helper.getRecentDao().queryBuilder().orderBy("timeStamp", false).where().eq("userId", MusicApplication.GetUserId()).queryForFirst();
            RecentAlbumRadioTrackBean recent = AlbumRadioAudioPlayer.get().getPlayMusic();
            if (recent != null) {


                if (PreferenceUtils.GetAudioFocusStatus()) {
                    stationInfo.setId(recent.getAlbumId());
                    stationInfo.setName(recent.getAlbumName());
                    stationInfo.setCoverUrlLarge(recent.getCover());
                    stationInfo.setCoverUrlSmall(recent.getCover());
                    stationInfo.setCoverUrlMiddle(recent.getCover());
                    stationInfo.setRadio("radio".equals(recent.getType()));
                    stationInfo.setProgramId(recent.getTrackId());
                    stationInfo.setProgramName(recent.getTrackName());
                    stationInfo.setProgramUrl(recent.getTrackUrl());
                    stationInfo.setHostName(recent.getAuthor());

                    FavouriteAlbumDbBean favData = DatabaseHelperOrm.getHelper(PlayAlbumRadioService.this).getFavouriteDao().queryBuilder().where().eq("userId", MusicApplication.GetUserId()).and().eq("id", AlbumRadioAudioPlayer.get().getPlayMusic().getAlbumId()).queryForFirst();
                    if (favData == null) {
                        stationInfo.setFavorite(false);
                    } else {
                        stationInfo.setFavorite(true);
                    }

                    result.setStationInfo(stationInfo);
                    result.setErrorCode("success");


                    if (AlbumRadioAudioPlayer.get().isPlaying()) {
                        result.setPlayStatus("playing");
                    } else {
                        result.setPlayStatus("paused");
                    }
                    result.setListType("favoriteList,downloadList,historyList,topList");
                    try {
                        resultOuter.setRequestResult(result);
                        SDSResponse.getInstance(this).sendResponse(requestId, new Gson().toJson(resultOuter), false);
                    } catch (RemoteException e) {
                        e.printStackTrace();
                    }
                } else {
                    result.setErrorCode("success");
                    stationInfo.setId(0);
                    stationInfo.setName("");
                    stationInfo.setCoverUrlLarge("");
                    stationInfo.setCoverUrlSmall("");
                    stationInfo.setCoverUrlMiddle("");
                    stationInfo.setRadio(false);
                    stationInfo.setProgramId(0);
                    stationInfo.setProgramName("");
                    stationInfo.setProgramUrl("");
                    stationInfo.setHostName("");
                    stationInfo.setFavorite(false);
                    result.setStationInfo(stationInfo);
                    try {
                        result.setListType("favoriteList,downloadList,historyList,topList");
                        result.setPlayStatus("paused");
                        resultOuter.setRequestResult(result);
                        Logger.i("PlayStatus-->" + new Gson().toJson(resultOuter));
                        SDSResponse.getInstance(this).sendResponse(requestId, new Gson().toJson(resultOuter), false);
                    } catch (RemoteException e) {
                        e.printStackTrace();
                    }
                }


            } else {
                result.setErrorCode("success");
                stationInfo.setId(0);
                stationInfo.setName("");
                stationInfo.setCoverUrlLarge("");
                stationInfo.setCoverUrlSmall("");
                stationInfo.setCoverUrlMiddle("");
                stationInfo.setRadio(false);
                stationInfo.setProgramId(0);
                stationInfo.setProgramName("");
                stationInfo.setProgramUrl("");
                stationInfo.setHostName("");
                stationInfo.setFavorite(false);
                result.setStationInfo(stationInfo);
                try {
                    result.setListType("favoriteList,downloadList,historyList,topList");
                    result.setPlayStatus("paused");
                    resultOuter.setRequestResult(result);
                    Logger.i("PlayStatus-->" + new Gson().toJson(resultOuter));
                    SDSResponse.getInstance(this).sendResponse(requestId, new Gson().toJson(resultOuter), false);
                } catch (RemoteException e) {
                    e.printStackTrace();
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }


    private void getAlbumTrack() {
        HashMap<String, Object> queryMaps = new HashMap<>();
        queryMaps.put("userId", MusicApplication.GetUserId());
        List<RecentAlbumRadioTrackBean> datas = null;
        try {
            datas = helper.getRecentDao().queryBuilder().orderBy("timeStamp", false).where().eq("userId", MusicApplication.GetUserId()).query();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        if (datas != null && datas.size() > 0) {
            RecentAlbumRadioTrackBean data = datas.get(0);
            radioModel.GetAlbumBrowse(data.getAlbumId(), 1).subscribe(new Subscriber<AlbumBrowseBean>() {
                @Override
                public void onCompleted() {

                }

                @Override
                public void onError(Throwable e) {

                }

                @Override
                public void onNext(AlbumBrowseBean albumBrowseBean) {
                    if ("0".equals(albumBrowseBean.getStatusCode())) {
                        AlbumRadioAudioPlayer.get().setOnSources(albumBrowseBean.getData().getTracks(), 0, 0, -1);
                        AlbumRadioAudioPlayer.get().play();
                    } else {
                        ToastUtils.show(albumBrowseBean.getStatusMessage());
                    }
                }
            });
        }
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return new PlayBinder();
    }

    public static void startCommand(Context context, String action) {
        Intent intent = new Intent(context, PlayAlbumRadioService.class);
        intent.setAction(action);
        context.startService(intent);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        if (intent != null && intent.getAction() != null) {
            switch (intent.getAction()) {
                case Actions.ACTION_STOP:
                    stop();
                    break;
                case CustomIntent.ACTION_SDS_COMMAND:
                    JSONObject jsonObject = null;
                    if (Constants.isRelease) {
//                        initAccountListener();
                    }
                    if (!TextUtils.isEmpty(intent.getStringExtra(CustomIntent.EXTRA_COMMAND))) {
                        try {
                            jsonObject = new JSONObject(intent.getStringExtra(CustomIntent.EXTRA_COMMAND));
                            String requestType = jsonObject.getString("requestType");
                            Logger.i(requestType);
                            String domain = jsonObject.getString("domain");
                            if ("onlineRadio".equals(domain)) {
//                                ToastUtils.show(requestType);
                                dealSDSCommand(intent.getStringExtra(CustomIntent.EXTRA_COMMAND), intent.getStringExtra(CustomIntent.EXTRA_REQUEST_ID));
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                    break;
                case CustomIntent.ACTION_LINUX2ANDROID_COMMAND:
                    dealTileCommand(intent.getStringExtra(CustomIntent.EXTRA_COMMAND));
                    break;
            }
        }

        try {
            List<FavouriteAlbumDbBean> local_db = new ArrayList<>();
            local_db.addAll(DatabaseHelperOrm.getHelper(PlayAlbumRadioService.this).getFavouriteDao().queryBuilder().orderBy("timeStamp", false).where().eq("userId", MusicApplication.GetUserId()).and().eq("type", "album").query());
            if (local_db.size() > 0) {
                if (local_db.get(0).getType().equals("album")) {

                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return START_NOT_STICKY;
    }

    private void dealTileCommand(String jsonAction) {
        Logger.i("dealTileCommand-->" + jsonAction);
        Constants.LastModeFlag=false;
        TileCommand command = new Gson().fromJson(jsonAction, TileCommand.class);
        if ("playPause".equals(command.getMediaAction())) {
//            AlbumRadioAudioPlayer.get().playPause();
//            if (AlbumRadioAudioPlayer.get().isPausing()) {
//                Constants.FLAG_PAUSE_MANUAL = true;
//                Constants.FLAG_FOCUS_ON_SELF = false;
//            }
//            if (AlbumRadioAudioPlayer.get().isPlaying()) {
//                Constants.FLAG_PAUSE_MANUAL = false;
//                Constants.FLAG_FOCUS_ON_SELF = true;
//            }

            Constants.LastModeFlag = false;
            if (AlbumRadioAudioPlayer.get().isPlaying()) {
                Constants.FLAG_PAUSE_MANUAL = true;
                Constants.FLAG_FOCUS_ON_SELF = false;
            }
            if (AlbumRadioAudioPlayer.get().isPausing()) {
                Constants.FLAG_PAUSE_MANUAL = false;
                Constants.FLAG_FOCUS_ON_SELF = true;
            }

            AlbumRadioAudioPlayer.get().playPauseAbandonFocus();
        } else if ("next".equals(command.getMediaAction())) {
            Constants.FLAG_PAUSE_MANUAL = false;
            AlbumRadioAudioPlayer.get().setOnpublishFlag(true);
            AlbumRadioAudioPlayer.get().next();
        } else if ("previous".equals(command.getMediaAction())) {
            Constants.FLAG_PAUSE_MANUAL = false;
            AlbumRadioAudioPlayer.get().setOnpublishFlag(true);
            AlbumRadioAudioPlayer.get().prev();
        }
    }

    private void stop() {
        AlbumRadioAudioPlayer.get().stopPlayer();
    }
}
